T
T
to_east2018-03-16 15:27:08
go
to_east, 2018-03-16 15:27:08

Embedded struct initialization?

Hello!
I'll give the code right away, then the analysis:

package main

import "fmt"

type Parent struct {
    foo int
}

type Child struct {
    Parent
    bar int
}

func main() {
    var parent = &Parent{ foo: 12 }
    var child = &Child{ parent, bar: 111 }
    child.Parent.foo++
    fmt.Println(parent.foo) // parent.foo should be 13
}

How to correctly initialize the Child structure, but also to be able to
change the foo field of the parent object through child.
The above code gives an initialization error:
C:\Windows\system32\cmd.exe /c (go run test1.go ^& pause)
# command-line-arguments
.\test1.go:18: mixture of field:value and value initializers
Для продолжения нажмите любую клавишу . . .

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
RidgeA, 2018-03-16
@to_east

https://play.golang.com/p/eiEplHj7sW__D

T
to_east, 2018-03-16
@to_east

It looks like I found a solution, but I'm not sure if it's correct, the code is:

package main


import "fmt"


type Parent struct {
    foo int
}

type Child struct {
    Parent *Parent
    bar int
}

func main() {
    var parent = &Parent{ foo: 12 }
    var child = &Child{ Parent: *&parent, bar: 111 }
    child.Parent.foo++
    fmt.Println(&parent.foo, &child.Parent.foo)
    fmt.Println(child.Parent.foo, parent.foo)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question