Skip to content

Instantly share code, notes, and snippets.

@fty4
Created October 8, 2019 13:21
Show Gist options
  • Select an option

  • Save fty4/6a8f1fe462e46a54fbfda3c8ffd39b88 to your computer and use it in GitHub Desktop.

Select an option

Save fty4/6a8f1fe462e46a54fbfda3c8ffd39b88 to your computer and use it in GitHub Desktop.
adds a value to a string-slice after a specific position
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