Last active
June 16, 2022 08:27
-
-
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.
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
// 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