Back to questions
JuniorTheoryCommon
What does the program print?
package main
import "fmt"
func main() {
a := [3]int{1, 2, 3}
b := a
b[0] = 9
fmt.Println(a[0], b[0])
}1 9
- Expecting
9 9, as ifbshared the array witha: assigning an array copies all its elements, so writing tob[0]leavesaunchanged. - Expecting a compile error, as in C, where arrays cannot be assigned: in Go
b := ais legal and copies the whole array.
- How would you make
bsee the same elements asa? - What happens to the caller's array when a function receives it as a
[3]intparameter and changes it?