Skip to content

Instantly share code, notes, and snippets.

@dimitrilw
Last active July 20, 2023 19:51
Show Gist options
  • Save dimitrilw/e188419ad023cdbcbfa4421b615bca95 to your computer and use it in GitHub Desktop.
Save dimitrilw/e188419ad023cdbcbfa4421b615bca95 to your computer and use it in GitHub Desktop.
golang filter slice
// 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