Go 转到,在函数中写入结构字段
我是Go新手,我不明白如果我不在结构函数中使用指针,为什么结构字段值不会被写入。这里是一个示例,当调用setValue时,它会执行,但未设置该值:Go 转到,在函数中写入结构字段,go,struct,Go,Struct,我是Go新手,我不明白如果我不在结构函数中使用指针,为什么结构字段值不会被写入。这里是一个示例,当调用setValue时,它会执行,但未设置该值: type myStruct struct { value string } func (m myStruct) getValue() string { return m.value } func (m myStruct) setValue(val string) { m.value = val } fu
type myStruct struct {
value string
}
func (m myStruct) getValue() string { return m.value }
func (m myStruct) setValue(val string) { m.value = val }
func (m *myStruct) getValuePointer() string { return m.value }
func (m *myStruct) setValuePointer(val string) { m.value = val }
func TestStruct(t *testing.T) {
obj := myStruct{value: "initValue"}
fmt.Printf("Use setValue function\n")
obj.setValue("setValue_Called")
fmt.Printf("obj.getValue() = [%v]\n", obj.getValue())
fmt.Printf("obj.getValuePointer() = [%v]\n", obj.getValuePointer())
fmt.Printf("Use setValuePointer function\n")
obj.setValuePointer("setValuePointer_Called")
fmt.Printf("obj.getValue() = [%v]\n", obj.getValue())
fmt.Printf("obj.getValuePointer() = [%v]\n", obj.getValuePointer())
}
此代码打印:
Use setValue function
obj.getValue() = [initValue]
obj.getValuePointer() = [initValue]
Use setValuePointer function
obj.getValue() = [setValuePointer_Called]
obj.getValuePointer() = [setValuePointer_Called]
有没有人能帮助我理解当使用或不使用指针创建结构函数时,在引擎盖下会发生什么?
此外,setValue执行时没有错误或警告的事实让我非常害怕:在定义方法时要记住的一件事是: 方法类似于普通函数,当您调用setValue函数时,发生的情况是这样的
package main
import "fmt"
type vertex struct {
x int
y int
}
func main() {
var v vertex
fmt.Println(v.setVertex(1, 2))
fmt.Println(v)
/* v = v.setVertex(1,2)
// we are assigning the returned variable address to v.
fmt.Println(v)
*/
}
// With a value receiver, the setVertex method operates on a copy of the
// original vertex value. (This is the same behavior as for any other
// function argument.)
// This methods has a value as a reciver, so it gets the copy not the
// original vertex.
func (v vertex) setVertex(x, y int) vertex {
// Here it is similar to creating a new variable with name 'v',
// Go is lexically scoped using blocks, so this variable exists only
// in this block, while it is returned we are printing it but we didn't
// store it in another variable.
v.x = x
v.y = y
return v
}
// If you want to change any variable or struct, we need to pass its
// address, else only copy of that variable is received by the called
// function.
这一点在中有明确的解释,是否有帮助,或者您在阅读后还有问题吗?该页面最重要的部分:使用值接收器,缩放方法对原始顶点值的副本进行操作。这与任何其他函数参数的行为相同。@smarx谢谢,它有帮助,但它并不能解决我对实际情况的所有疑问。对于值接收器,缩放方法对原始顶点值的副本进行操作到底意味着什么。?这是否意味着将动态创建结构的新实例,并且所有原始实例字段将递归复制?因此,如果一个巨大的对象作为值接收器传递,它可以填满所有可用的内存?是的,你的理解基本上是正确的。这是100%的重复。这个问题经常被问到,因为互联网上有很多解释,包括围棋的官方文档。