Skip to content

Instantly share code, notes, and snippets.

@nikzayn
Last active June 16, 2022 08:27
Show Gist options
  • Save nikzayn/703af3d78fdfef632d609acc95c12100 to your computer and use it in GitHub Desktop.
Save nikzayn/703af3d78fdfef632d609acc95c12100 to your computer and use it in GitHub Desktop.
A brief example of how we can achieve composition in go. Composition is not anything like inheritance it's just embed one struct to another to maintain data inheritance in it's own way.
// Person struct
type Person struct {
FirstName string
LastName string
Age int
TotalExperience int
}
// Person struct embedded in Job struct
type Job struct {
Skill string
Hobbies string
JobTitle string
Person
}
func (p Person) getName() string {
return p.FirstName + " " + p.LastName
}
func (j Job) candidateEligibility() string {
if j.JobTitle == "Software Engineer" && j.Skill == "Golang" && j.TotalExperience == 3 {
return "You're eligible for this job."
}
return "Sorry, you're not eligible. Best of luck!"
}
func main() {
personData := Person{
FirstName: "Nikhil",
LastName: "Vaidyar",
Age: 25,
TotalExperience: 3,
}
jobData := Job{
Skill: "Golang",
Hobbies: "Travelling",
JobTitle: "Software Engineer",
Person: personData,
}
fmt.Println(jobData.getName())
fmt.Println(jobData.candidateEligibility())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment