Last active
September 4, 2018 17:38
-
-
Save bmcculley/47c9de54d91571d9a54167b9de9e2603 to your computer and use it in GitHub Desktop.
Example of a golang string slice and element removal by index (https://play.golang.org/p/Kw20T6apfLP)
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" | |
"sort" | |
) | |
func remove(slice []string, s int) []string { | |
return append(slice[:s], slice[s+1:]...) | |
} | |
func index(data []string, term string) (int, bool) { | |
idx := sort.Search(len(data), func(i int) bool { | |
return string(data[i]) >= term | |
}) | |
if idx < len(data) && data[idx] == term { | |
return idx, true | |
} else { | |
return 0, false | |
} | |
} | |
func main() { | |
a := []string{"Hello", "golang", "world"} | |
fmt.Printf("%v\n", a) | |
fmt.Println(a[1]) | |
b := remove(a, 2) | |
fmt.Printf("%v\n", b) | |
idx, ok := index(a, "golang") | |
if ok { | |
fmt.Println(a[idx]) | |
} else { | |
fmt.Println("oops, there's nothing there.") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment