Struct Embedding
This Go program demonstrates the concept of composition in Go structs, where a struct includes another struct as a field. It also showcases method overriding through embedding and interface implementation. Let's go through each part of the code with inline comments and additional explanations:
Output
Explanation:
The
base
struct has a single field,num
, and a method calleddescribe
that returns a string describing the base struct.The
container
struct embeds thebase
struct, effectively inheriting its fields and methods. It also has an additional field,str
.In the
main
function:An instance
co
of thecontainer
struct is created with field values.Field values of the
container
struct are printed, and the embeddedbase
struct field (num
) is accessed directly.The
describe
method is called on thecontainer
struct, which internally calls thedescribe
method of the embeddedbase
struct.An interface named
describer
is defined with adescribe
method.A variable
d
of typedescriber
is created and assigned thecontainer
struct.The
describe
method is called on thedescriber
interface, demonstrating method overriding. The overridden method in thecontainer
struct is called.
Last updated
Was this helpful?