Golang, Go: why does the pointer use the star operator instead of &

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) } 

Well, I understand why and how a pointer works, but I always wondered why we use the * operator to pass a pointer to a function.

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

Why don't we use &ByteSlice to pass a pointer to a function?

I am embarrassed. Doesn't this function pass a pointer?

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

PointerType = "*" BaseType.

BaseType = Type.

It bothers me too. Why do we use the star ( * ) operator to get a variable pointer and a dereference pointer? It looks like we are not using & for this case in either C or Go ...

+6
source share
1 answer

* in func (p *ByteSlice) Append(data []byte) { just declares that p is of type *ByteSlice .

The passage of the pointer occurs here:

 x.Append(y) 

As Specified (my emphasis):

The method xm () call is valid if the set of methods (type) x contains m, and the argument list can be assigned to the parameter list m. If x is addressed, and the set of methods & x contains m, xm () is short for (& x) .m ():

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

+10
source

All Articles