How to initialize a composite structure in Go?

Let's say I have a structure with another structure built into it.

type Base struct { ID string } type Child struct { Base a int b int } 

When I go to initialize the Child , I cannot initialize the ID field directly.

 // unknown field 'ID' in struct literal of type Child child := Child{ ID: id, a: a, b: b } 

Instead, I have to initialize the identifier field separately.

 child := Child{ a: 23, b: 42 } child.ID = "foo" 

This would seem to violate encapsulation. Child must know something else in the ID field. If I later moved the public field to the inline structure, this could break the initialization.

I could write a NewFoo() method for each structure and hope everyone uses this, but is there a way to use the struct literal safely with inline structures that don't show that some of the fields are embedded? Or am I using the wrong template here?

+5
source share
1 answer

Use nested compound literals to initialize a value in a single expression:

 child := Child{Base: Base{ID: id}, a: a, b: b} 

It is impossible to hide the fact that the field is advancing from the built-in structure.

+13
source

Source: https://habr.com/ru/post/1268118/


All Articles