4

I am trying to append a vertex into the a slice of vertex by passing the pointer of that slice to the function AppendVertex, I know how to get the length of an array by using len function, but is there any way to get the the length of pointer array ?

type Vertex struct {
    X int
    Y int
}

func main() {
    var v []Vertex
    fmt.Println(len(v))
    appendVertex(&v)
    fmt.Println(len(v))

}

func appendVertex(v *[]Vertex) {

    *v = append(*v, Vertex{1, 1})

    fmt.Println(len(v))
}

Result for this one is

prog.go:22:16: invalid argument v (type *[]Vertex) for len

I also did another version by passing the pointer to the slice, however the size of slice did not changed, should't the slice is a reference type structure ? why does the size did not changed here

type Vertex struct {
    X int
    Y int
}

func main() {
    var v []*Vertex
    fmt.Println(len(v))
    appendVertex(v)
    fmt.Println(len(v))

}

func appendVertex(v []*Vertex) {

    v = append(v, &Vertex{1, 1})

    fmt.Println(len(v))
}
​

Result for second one is

0
1
0
wasmup
  • 14,541
  • 6
  • 42
  • 58
YuanZheng Hu
  • 339
  • 2
  • 3
  • 14
  • Possible duplicate of [Golang append an item to a slice](https://stackoverflow.com/questions/20195296/golang-append-an-item-to-a-slice) – Peter Apr 12 '18 at 06:56

1 Answers1

15

If you want the length of the thing that v points to, do:

fmt.Println(len(*v))

https://play.golang.org/p/JIWxA2BnoTL

in your second example, you are passing a slice, which contains a length, capacity, and a pointer to the slices first element in the backing array. If you modify an element, it will be modified in both (since the copy of the pointer will still point to the same backing array), but if you append, you are creating a new slice (I believe), but even if not, your original slices length would make it end before the new element regardless.

dave
  • 62,300
  • 5
  • 72
  • 93
  • 1
    append *may* create a new slice header. That happens if the backing array does not have enough capacity for the new elements. See https://blog.golang.org/slices for all the gory details. – Peter Apr 12 '18 at 07:02