5

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
1

1 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

1 Comment

append may create a new slice header. That happens if the backing array does not have enough capacity for the new elements. See blog.golang.org/slices for all the gory details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.