notexOPENOverview
Notex/Languages/Converting Arrays to Slices
01.12LESSON 12 OF 33 · 1 MIN READ

Converting Arrays to Slices

Always free to read

Slices aren’t the only thing you can slice. If you have an array, you can take a slice from it using a slice expression. This is a useful way to bridge an array to a function that takes only slices. To convert an entire array into a slice, use the [:] syntax:

xArray := [4]int{5, 6, 7, 8}
xSlice := xArray[:]

You can also convert a subset of an array into a slice:

x := [4]int{5, 6, 7, 8}
y := x[:2]
z := x[2:]

Be aware that taking a slice from an array has the same memory-sharing properties as taking a slice from a slice. If you run the following code on The Go Playground:

x := [4]int{5, 6, 7, 8}
y := x[:2]
z := x[2:]
x[0] = 10
fmt.Println("x:", x)
fmt.Println("y:", y)
fmt.Println("z:", z)

you get this output:

x: [10 6 7 8]
y: [10 6]
z: [7 8]

You can use copy with arrays by taking a slice of the array. You can make the array either the source or the destination of the copy. You can try out the following code on The Go Playground:

x := []int{1, 2, 3, 4}
d := [4]int{5, 6, 7, 8}
y := make([]int, 2)
copy(y, d[:])
fmt.Println(y)
copy(d[:], x)
fmt.Println(d)

The first call to copy copies the first two values in array d into slice y. The second copies all of the values in slice x into array d. This produces the following output:

[5 6]
[1 2 3 4]
Progress is saved on this device.
KEEP EXPLORING

One note leads to another.

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