Back to questions
JuniorTheoryCommon
What does the program print?
package main
import "fmt"
func main() {
s := make([]int, 3)
s = append(s, 7)
fmt.Println(len(s), s)
}4 [0 0 0 7]
- Expecting
1 [7], as ifmake([]int, 3)only reserved room: it creates three elements set to zero, andappendadds7after them. - Expecting
appendto fill the first zero: zeros are ordinary elements, soappendalways writes after the last one and the length grows to4.
- How would you change the
makecall so that the program prints1 [7]? - Why must the result of
appendbe assigned back tos?