How to delete an empty value in a slice in golang?
Published: Monday, Apr 6, 2015 Last modified: Monday, Dec 9, 2024
There is no delete in a slice, since in golang slices are not that high level. You can think of them as variable-length c arrays. Do take time to read http://blog.golang.org/go-slices-usage-and-internals
Given a slice like:
s := []string{"foo", "", "bar", ""}
https://play.golang.org/p/7RzNelz947
How do you remove the empty values simply? i.e. printing an end result:
["foo" "bar"]
https://play.golang.org/p/fxVyC4WqjR
func delete_empty (s []string) []string {
var r []string
for _, str := range s {
if str != "" {
r = append(r, str)
}
}
return r
}
Alternatively
Another approach is to define a helper function, ala https://play.golang.org/p/Xcno8QurAn