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/