c - 戈朗,围棋 : why pointer use star operator instead of &

标签 c pointers go

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

好吧,我明白指针为什么以及如何工作,但我一直想知道为什么我们使用 * 运算符将指针传递给函数。

  • *ptr是对ptr进行引用,返回指针ptr中保存的值。
  • &var 返回变量 var 的地址。

为什么我们不使用&ByteSlice 将指针传递给函数?

我很困惑。这个函数不是传递指针吗?

根据 Go 规范 ( http://golang.org/ref/spec#Pointer_types )

PointerType = "*" BaseType .

BaseType = Type .

这也让我很困惑。为什么我们使用 star(*) 运算符来获取变量指针和解引用指针?看起来我们在 C 和 Go 中都没有对这种情况使用 &...

最佳答案

func (p *ByteSlice) Append(data []byte) { 中的 * 只是声明 p 的类型为 *ByteSlice.

指针的传递发生在这里:

x.Append(y)

作为Specification说(我的重点):

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():

在您的例子中,x.Append(y)(&x).Append(y) 的简写。你有你的 &-标志。

关于c - 戈朗,围棋 : why pointer use star operator instead of &,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21452165/

相关文章:

c - 如何处理严格的别名警告

字符串匹配的 C 代码 [Head First C] 似乎不起作用

mysql - 零到多 : Cannot add or update a child row: a foreign key constraint fails

c++ - 尝试使用指向结构 vector 的指针访问结构类型时出错

delphi - 为什么会出现内存泄漏以及如何修复它?

go - Golang append() 受 fmt.Println() 影响的奇怪行为

go - 如何将 int32 unicode 转换为字符串

c++ - 按位 - 如何检查一个二进制数是否包含另一个?

c - 为什么我们不能从 C 中的函数返回多个值?请问原因?

c - 在以下 lex/yacc 文件中接收段错误(核心转储)。他们怎么了?