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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!