dongqiabei7682
dongqiabei7682
2014-01-30 09:17
浏览 310
已采纳

Golang Go:为什么指针使用星号运算符而不是&

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongrou5254
    dongrou5254 2014-01-30 09:37
    已采纳

    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.

    点赞 评论

相关推荐