package main
import (
"fmt"
)
type Person struct {
name string
}
func main() {
p := make([]*Person, 0)
p = append(p, &Person{"Brian"})
fmt.Println(p[0].name)
p = append(p, &Person{"Le Tu"})
fmt.Println(p[1].name)
}
The above works fine.
package main
import (
"fmt"
)
type Person struct {
name string
}
func main() {
p := make([]*Person, 1) //Changed to 1 instead of 0
p = append(p, &Person{"Brian"})
fmt.Println(p[0].name)
p = append(p, &Person{"Le Tu"})
fmt.Println(p[1].name)
}
The above panics.
My understanding of append
was that it hid the mechanics of extending/adding. Clearly, my mental model of using append
as a sort of "push" for slices is incorrect. Can anyone explain to me why the second sample above panics? Why can't I just append
my struct?