Golang中通过方法更新结构体字段值的最佳实践
Golang中通过方法更新结构体字段值的最佳实践 请问有人能告诉我,通过方法更新结构体中的值的最佳方式是什么吗?
在下面的示例代码中,move() 方法的目的是:
- 移动一扇门(实际移动的代码尚未包含在示例中)
- 更新结构体中的
position值
更新后的 position 没有在 door1 中反映出来,我推测是由于方法内变量的作用域(?)导致的。最后一行预期的输出应该是 “open”,但 door1.position 并未相应更新。
我不确定确保 door1.position 正确更新的最佳方式是什么?
提前感谢。
package main
import "fmt"
type door struct {
position string
}
func (d door) move() {
// Open door
d.position = "open"
fmt.Printf("Door position is changed to %s\n", d.position)
}
func main() {
door1 := door{"closed"}
door1.move()
fmt.Printf("Door is %s\n", door1.position)
//Expected: "open", Result: "closed
}
更多关于Golang中通过方法更新结构体字段值的最佳实践的实战教程也可以访问 https://www.itying.com/category-94-b0.html
3 回复
感谢您的解释。我原本以为必须使用指针,您的文章对我帮助很大,谢谢!
更多关于Golang中通过方法更新结构体字段值的最佳实践的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Go语言中,你的问题是由于方法使用了值接收器(value receiver)导致的。当使用值接收器时,方法操作的是结构体的副本,而不是原始实例。要更新原始结构体的字段,需要使用指针接收器(pointer receiver)。
以下是修改后的代码示例:
package main
import "fmt"
type door struct {
position string
}
// 使用指针接收器来修改原始结构体的字段
func (d *door) move() {
// Open door
d.position = "open"
fmt.Printf("Door position is changed to %s\n", d.position)
}
func main() {
door1 := door{"closed"}
door1.move() // Go会自动将door1转换为&door1
fmt.Printf("Door is %s\n", door1.position)
// 现在输出: "open"
}
或者,你也可以显式地使用指针调用方法:
func main() {
door1 := &door{"closed"} // 创建指针
door1.move()
fmt.Printf("Door is %s\n", door1.position)
}
两种方式都能正确更新door1.position的值。使用指针接收器是更新结构体字段值的标准做法,特别是在需要修改结构体状态时。


