Last active
July 20, 2023 19:51
-
-
Save dimitrilw/e188419ad023cdbcbfa4421b615bca95 to your computer and use it in GitHub Desktop.
golang filter slice
This file contains 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
// remember that "slice magic" means that the underlying array of data | |
// beyond the 'i'th value may still be available, so the slice should not | |
// be exported outside of the package, like to third-party software | |
func demoFilter(s []int) []int { | |
i := 0 | |
for _, v := range s { | |
if v > 1 { // some criteria; this is the filter | |
s[i] = v | |
i++ | |
} | |
} | |
return s[:i] | |
} | |
func demoMain() { | |
x := demoFilter([]int{1,2,3,0,1,8,9}) | |
fmt.Println(x) | |
} | |
// out: [2 3 8 9] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment