MiddleCodeOccasionalNot answered yet
After these index writes through y and z, what do x, y and z print?
Trace each index write through the reslices and give the three printed lines.
func slicesSharedMem() {
x := []string{"a", "b", "c", "d"}
y := x[:2]
z := x[1:]
x[1] = "y"
y[0] = "x"
z[1] = "z"
fmt.Println("x:", x)
fmt.Println("y:", y)
fmt.Println("z:", z)
}
Predict the output.
It prints x: [x y z d], y: [x y], z: [y z d]. Both y := x[:2] and z := x[1:] reslice x, so they share its backing array. x[1]="y", y[0] writes x[0]="x", and z[1] writes x[2]="z", all visible through every overlapping range.
- ✗Assuming reslices copy elements —
x[:2]andx[1:]viewx's same backing array - ✗Mapping
z[1]toxindex 1 instead of 2 —zstarts at offset 1, soz[1]isx[2] - ✗Expecting a panic — every index here is within each slice's length
- →How would the result change if
ywere built withcopyinstead ofx[:2]? - →Why does
z[1]map tox[2]rather thanx[1]?
Contents
What does this code print?
x := []string{"a", "b", "c", "d"}
y := x[:2]
z := x[1:]
x[1] = "y"
y[0] = "x"
z[1] = "z"
Output
x: [x y z d]
y: [x y]
z: [y z d]
Why every slice sees the writes
y := x[:2] and z := x[1:] are reslices of x: they do not copy elements, they view the same backing array. Their offsets relative to x:
ystarts at index 0 (y[0]↔x[0]).zstarts at index 1 (z[1]↔x[2]).
Replaying the writes against x:
x[1] = "y"→x = [a y c d].y[0] = "x"writesx[0]→x = [x y c d].z[1] = "z"writesx[2]→x = [x y z d].
Final: x = [x y z d], y = x[:2] = [x y], z = x[1:] = [y z d]. </content>
Contents