Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you append a pointer to an array?

Tags:

pointers

go

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.

like image 706
Shail Patel Avatar asked Jun 22 '26 04:06

Shail Patel


2 Answers

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.

like image 96
hobbs Avatar answered Jun 23 '26 19:06

hobbs


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

like image 41
aerth Avatar answered Jun 23 '26 17:06

aerth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!