英文:
How to change both inner and original struct in a nested struct
问题
我是你的中文翻译助手,以下是翻译好的内容:
我刚开始学习Go语言,正在尝试理解嵌套结构体的可变性是如何工作的。
我创建了一个带有嵌套结构体的小测试。我想要做的是能够编写像outer.inner.a = 18
这样的代码,它可以同时改变inner.a
和outer.inner.a
。
这种操作是否可行?或者结构体的工作方式与此不同?也许我应该使用指向内部结构体的指针?我之前有面向对象编程的经验,所以对于修改子对象的逻辑对我来说很直观。在Go语言中是否有所不同?
输出结果:
{1}
{3 {1}}
{18}
{3 {1}} // 我希望这里是{3 {18}}
{18} // 我希望这里是{22}
{3 {22}}
https://go.dev/play/p/tD5S5k2eJLp?v=gotip
英文:
I am new to Go and I am trying to understand how the mutability of nested structs work.
I created a little test with a nested struct. What I want to do is able to write code like outer.inner.a = 18
which changes both inner.a
and outer.inner.a
.
Is this possible or is it not how structs work? Should I maybe use a pointer to the inner struct instead? I have worked with OOP so this logic of modifying a child object is intuitive for me. Is it different in Go?
package main
import "fmt"
type innerStruct struct {
a int
}
type outerStruct struct {
b int
inner innerStruct
}
func main() {
inner := innerStruct{1}
outer := outerStruct{3, inner}
fmt.Println(inner)
fmt.Println(outer)
inner.a = 18
fmt.Println(inner)
fmt.Println(outer)
outer.inner.a = 22
fmt.Println(inner)
fmt.Println(outer)
}
Output:
{1}
{3 {1}}
{18}
{3 {1}} // I want {3 {18}} here
{18} // I want {22} here
{3 {22}}
答案1
得分: 2
golang总是按值复制而不是引用,你可以使用指针来实现:
type innerStruct struct {
a int
}
type outerStruct struct {
b int
inner *innerStruct
}
英文:
golang always copy by value not quote,you can use Pointer like
type innerStruct struct {
a int
}
type outerStruct struct {
b int
inner *innerStruct
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论