Created
January 22, 2017 07:59
-
-
Save ta1kt0me/22609870436dab39cd35a5e6d2da28d7 to your computer and use it in GitHub Desktop.
Create slice filtering some condition from array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import "fmt" | |
| func main() { | |
| s := []int{2, 3, 5, 7, 11, 13} | |
| printSlice(s) | |
| // https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating | |
| ns := s[:0] | |
| for _, v := range s { | |
| if v % 3 == 2 { | |
| ns = append(ns, v) | |
| } | |
| } | |
| printSlice(ns) | |
| } | |
| func printSlice(s []int) { | |
| fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment