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.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?