package main
import "fmt"
type Circle struct {
x string
}
func main() {
circle := Circle{x: "blah"}
results := make([]*Circle, 1)
results = append(results, &circle)
fmt.Printf("Here: %s\n", results[0].x)
}
If I change the line results = append(results, &circle) to results[0] = &circle works fine. Couldn't find any reason as to why that would be.
You can, it's just that you are appending to the slice, which means that the element you add is in results[1], and results[0] is a nil pointer (the default value for a pointer).
You could do results := make([]*Circle, 0, 1) to give it a capacity of 1 but a length of zero, or you could do results := []*Circle{} (most compact), or you could simply keep the version where you assign to results[0], since it works just fine.
You can, but you are using make with length 1, so the [0] index is already set (to a nil Circle...)
Changing your results[0].x to results[1].x works, but without using make works as expected:
package main
import "fmt"
type Circle struct {
x string
}
func main() {
circle := Circle{x: "blah"}
results := []*Circle{} // initialize empty slice of Circle pointers
results = append(results, &circle)
fmt.Printf("Here: %s\n", results[0].x)
}
Run in playground: https://play.golang.org/p/7vMOfAXvgI
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With