Search⌘ K
AI Features

Solution Review: Inserting Slice in a Slice

Understand how to insert one slice into another at any given position in Go by using the copy function. Explore a step-by-step code solution that creates a new slice, copies elements before and after the insertion point, and returns the updated slice. This lesson helps you master slice manipulation for more dynamic Go programming.

We'll cover the following...
Go (1.6.2)
package main
import (
"fmt"
)
func main() {
s := []string{"M", "N", "O", "P", "Q", "R"}
in := []string{"A", "B", "C"}
res := insertSlice(s, in, 0) // at the front
fmt.Println(res) // [A B C M N O P Q R]
res = insertSlice(s, in, 3) // [M N O A B C P Q R]
fmt.Println(res)
}
func insertSlice(slice, insertion []string, index int) []string {
result := make([]string, len(slice) + len(insertion))
at := copy(result, slice[:index])
at += copy(result[at:], insertion)
copy(result[at:], slice[index:])
return result
}

In the code above, look at the header for the function insertSlice at line 15: insertSlice(slice, insertion []string, index int) []string. This function takes two slices slice (the slice in ...