slice 2

What does the following program print?
package main

func main() {
	var x = []string{"A", "B", "C"}

	for i, s := range x {
		print(i, s, ",")
		x[i+1] = "M"
		x = append(x, "Z")
		x[i+1] = "Z"
	}
}

Choices:

Answer: 0A,1M,2C,

Run it on Go play.

Key points:

This above quiz is extended from one of Valentin Deleplace's quizzes. The following is the original quiz.

package main

func main() {
	var x = []string{"A", "B", "C"}

	for i, s := range x {
		print(i, s, " ")
		x = append(x, "Z")
		x[i+1] = "Z"
	}
}

The original quiz prints 0A,1B,2C,, because the ranged container is a copy of the initial x, and elements of the copy are never changed.

The following is another quiz made by Valentin Deleplace (with a bit modification).

package main

func main() {
	var y = []string{"A", "B", "C", "D"}
	var x = y[:3]

	for i, s := range x {
		print(i, s, ",")
		x = append(x, "Z")
		x[i+1] = "Z"
	}
}

The other quiz prints 0A,1Z,2C,. It is similar to the above extened quiz. Key points: