Created
October 8, 2019 13:21
-
-
Save fty4/6a8f1fe462e46a54fbfda3c8ffd39b88 to your computer and use it in GitHub Desktop.
adds a value to a string-slice after a specific position
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() { | |
| var a,b []string | |
| a = []string{"a","b","d","e"} | |
| fmt.Println("a (before):") | |
| fmt.Println(a) | |
| fmt.Println() | |
| b = insertSliceAfter(a, "c", 2) | |
| fmt.Println("a (after):") | |
| fmt.Println(a) | |
| fmt.Println() | |
| fmt.Println("b:") | |
| fmt.Println(b) | |
| } | |
| func insertSliceAfter(slice []string, value string, pos int) []string { | |
| s := make([]string, len(slice)) | |
| copy(s, slice) | |
| s = append(s, "") | |
| copy(s[pos+2:], s[pos+1:]) | |
| s[pos+1] = value | |
| return s | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment