Solution Review: Inserting Slice in a Slice
This lesson discusses the solution to the challenge given in the previous lesson.
We'll cover the following...
Press + to interact
package mainimport ("fmt")func main() {s := []string{"M", "N", "O", "P", "Q", "R"}in := []string{"A", "B", "C"}res := insertSlice(s, in, 0) // at the frontfmt.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 which another slice will be inserted) and insertion
(the slice that is to be inserted in slice) and an integer parameter index
that defines the point of insertion. The function returns an updated slice after insertion.
We make a slice called result
at line 16 with the make
function. The length of the ...