如何在嵌套结构中同时更改内部结构和原始结构。

huangapple go评论98阅读模式
英文:

How to change both inner and original struct in a nested struct

问题

我是你的中文翻译助手,以下是翻译好的内容:

我刚开始学习Go语言,正在尝试理解嵌套结构体的可变性是如何工作的。
我创建了一个带有嵌套结构体的小测试。我想要做的是能够编写像outer.inner.a = 18这样的代码,它可以同时改变inner.aouter.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}}

https://go.dev/play/p/tD5S5k2eJLp?v=gotip

答案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
}

huangapple
  • 本文由 发表于 2022年4月14日 09:53:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/71865621.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定