notexOPENOverview
Notex/Languages/Copying Slices of Slices
01.11LESSON 11 OF 33 · 1 MIN READ

Copying Slices of Slices

Always free to read

Slice expressions allow you to copy from the middle of the source slice:

x := []int{1, 2, 3, 4}
y := make([]int, 2)
copy(y, x[2:])

You are copying the third and fourth elements in x by taking a slice of the slice. Also note that you don’t assign the output of copy to a variable. If you don’t need the number of elements copied, you don’t need to assign it.

Combining the copy function with slice expressions allows you to do some unusual things, like copy between two slices that cover overlapping sections of an underlying slice:

x := []int{1, 2, 3, 4}
num := copy(x[:3], x[1:])
fmt.Println(x, num)

In this case, you are copying the last three values in x on top of the first three values of x. This prints out [2 3 4 4] 3.

Progress is saved on this device.
KEEP EXPLORING

One note leads to another.

Back to the library →
⌕
Search across the entire library ⌘ K