Home > Enterprise >  How to change both inner and original struct in a nested struct
How to change both inner and original struct in a nested struct

Time:04-15

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

CodePudding user response:

golang always copy by value not quote,you can use Pointer like

type innerStruct struct {
    a int
}

type outerStruct struct {
    b     int
    inner *innerStruct
}
  • Related