11

The code:

type ByteSlice []byte

func (p *ByteSlice) Append(data []byte) {
  slice := *p
  slice = append(slice, data...)
  *p = slice
}

func main() {
  x := ByteSlice{1, 2, 3}
  y := []byte{4, 5}
  x.Append(y)
  fmt.Println(x)
}

Ok, I understand why and how pointer works, but I've always wondered why we use * operator to pass pointer to function.

  • *ptr is to deference the ptr and return the value saved in the pointer ptr.
  • &var returns the address of the variable var.

Why we do not use &ByteSlice to pass pointer to function?

I am confused. Isn't this function passing pointer?

According to Go spec (http://golang.org/ref/spec#Pointer_types)

PointerType = "*" BaseType .

BaseType = Type .

This also confuses me. Why we use star(*) operator both to get the pointer of variable and dereference pointer? Looks like we don't use & for this case both in C and Go...

kostix
  • 51,517
  • 14
  • 93
  • 176
  • 2
    The use of `*` instead of `&` in pointer declarations stems for the C principle that [declaration syntax follows usage](http://stackoverflow.com/q/3707096/166749). – Fred Foo Jan 30 '14 at 10:29

1 Answers1

16

The * in func (p *ByteSlice) Append(data []byte) { is simply declaring that p is of type *ByteSlice.

The passing of a pointer takes place here:

x.Append(y)

As the Specification says (my emphasis):

A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m. If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m():

In your case, x.Append(y) is a shorthand for (&x).Append(y). There you have your &-sign.

ANisus
  • 74,460
  • 29
  • 162
  • 158
  • Thanks, I think my question is more C syntax. I was confused by * which also can be used to dereference pointer. * can do both? One to dereference pointer, and the other to get the pointer of invoked variable? –  Jan 30 '14 at 09:40
  • 2
    Yes. * is used in declaration to say that `*ByteSlice` is a pointer to a ByteSlice. And it is also used for dereference a pointer, (*p). However, * is never used to retrieve a pointer; & will be used for that. – ANisus Jan 30 '14 at 09:45
  • What do you mean by 'retrieve' a pointer? You mean to retrieve a pointer of variable, we only use & operator? like &num? –  Jan 30 '14 at 09:47
  • I see! "& will be used for that" Good to know! Everything is clear now! –  Jan 30 '14 at 09:48
  • 1
    Exactly :) . Sorry, I added that last sentence in an edit. Glad to help! – ANisus Jan 30 '14 at 09:49