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...