JuniorCodeOccasionalNot answered yet
What does this slice-expression snippet print for x, y, z, d and e?
Work out each printed line and explain what x[low:high] selects.
func slicesExample() {
x := []string{"a", "b", "c", "d"}
y := x[:2]
z := x[1:]
d := x[1:3]
e := x[:]
fmt.Println("x:", x)
fmt.Println("y:", y)
fmt.Println("z:", z)
fmt.Println("d:", d)
fmt.Println("e:", e)
}
Predict the output.
It prints x: [a b c d], y: [a b], z: [b c d], d: [b c], e: [a b c d]. The form x[low:high] yields elements from index low up to high-1, so its length is high-low; an omitted bound defaults to 0 or len(x).
- ✗Treating the
highbound as inclusive —x[1:3]returns indices 1 and 2, not 1, 2, 3 - ✗Forgetting that an omitted low defaults to
0and an omitted high tolen(x) - ✗Assuming
x[:]copies the array — it returns a slice over the same backing array
- →What capacity does
y := x[:2]have, and why is it not 2? - →How would you copy the elements so the result does not share
x's backing array?
Contents
What does this code print?
x := []string{"a", "b", "c", "d"}
y := x[:2]
z := x[1:]
d := x[1:3]
e := x[:]
Output
x: [a b c d]
y: [a b]
z: [b c d]
d: [b c]
e: [a b c d]
How to read a slice expression
The expression x[low:high] is half-open: it takes elements from index low up to and including high-1, and the result has length high-low.
y := x[:2]— omitted low is0: indices 0..1 →[a b].z := x[1:]— omitted high islen(x): indices 1..3 →[b c d].d := x[1:3]— indices 1..2 →[b c].e := x[:]— both ends omitted: the whole slice →[a b c d].
⚠️ x[:] does not copy the array — all of these slices share one backing array with x. To get an independent copy, use copy or append into a new slice. </content> </invoke>
Contents