Last active
October 18, 2025 22:06
-
-
Save Clivern/b90a6981a74ab1cccc54386ad91db89f to your computer and use it in GitHub Desktop.
Go Embedding Structs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Package main demonstrates object composition and encapsulation in Go. | |
| // It defines a Citizen type and a Student type that embeds Citizen, | |
| // providing getter and setter methods for each field. | |
| package main | |
| import ( | |
| "fmt" | |
| ) | |
| // Citizen represents a person with basic personal identifiers. | |
| type Citizen struct { | |
| name string | |
| age int | |
| bsn string | |
| } | |
| // SetName assigns a new name to the citizen. | |
| func (c *Citizen) SetName(name string) { | |
| c.name = name | |
| } | |
| // SetAge assigns an age to the citizen. | |
| func (c *Citizen) SetAge(age int) { | |
| c.age = age | |
| } | |
| // SetBsn assigns a BSN (Dutch national identification number) to the citizen. | |
| func (c *Citizen) SetBsn(bsn string) { | |
| c.bsn = bsn | |
| } | |
| // GetName returns the citizen's name. | |
| func (c *Citizen) GetName() string { | |
| return c.name | |
| } | |
| // GetAge returns the citizen's age. | |
| func (c *Citizen) GetAge() int { | |
| return c.age | |
| } | |
| // GetBsn returns the citizen's BSN. | |
| func (c *Citizen) GetBsn() string { | |
| return c.bsn | |
| } | |
| // Student represents a person who is also enrolled at a school. | |
| // It embeds Citizen to inherit personal details. | |
| type Student struct { | |
| Citizen | |
| school string | |
| } | |
| // GetSchool returns the student's school name. | |
| func (s *Student) GetSchool() string { | |
| return s.school | |
| } | |
| // SetSchool assigns a school name to the student. | |
| func (s *Student) SetSchool(school string) { | |
| s.school = school | |
| } | |
| // NewStudent creates and returns a pointer to a Student instance | |
| // with the specified name, age, BSN, and school. | |
| func NewStudent(name string, age int, bsn string, school string) *Student { | |
| return &Student{ | |
| Citizen: Citizen{ | |
| name: name, | |
| age: age, | |
| bsn: bsn, | |
| }, | |
| school: school, | |
| } | |
| } | |
| // main demonstrates creation and manipulation of a Student object. | |
| func main() { | |
| s := NewStudent("Joe", 69, "X-X-X", "Almere") | |
| s.SetName("Doe") | |
| s.SetBsn("Y-Y-Y") | |
| fmt.Println(s.GetName()) // Output: Doe | |
| fmt.Println(s.GetAge()) // Output: 69 | |
| fmt.Println(s.GetSchool()) // Output: Almere | |
| fmt.Println(s.GetBsn()) // Output: Y-Y-Y | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.