Last active
June 15, 2022 13:28
-
-
Save nikzayn/c3c96156a84355ffd84f9a90619b320c to your computer and use it in GitHub Desktop.
A brief example of how we can use principle of encapsulation in Go
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 details | |
import ( | |
fmt | |
person "github.com/nikzayn/encapsulation/user" | |
) | |
func main() { | |
fmt.Println(person.GetDateOfBirth()) // 1989 | |
fmt.Println(person.getFoodStatus()) // Not declared by package because it is small caps | |
} |
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 person | |
import ( | |
"fmt" | |
"time" | |
) | |
type Person struct { | |
Name string | |
Age int | |
DoesShareFood bool | |
} | |
func (p *Person) GetDateOfBirth() int { | |
return time.Now().Year() - p.Age | |
} | |
func (p *Person) getFoodStatus() bool { | |
return p.DoesShareFood | |
} | |
func main() { | |
person := Person { | |
Name: "Joey", | |
Age: 33, | |
DoesShareFood: No, | |
} | |
fmt.Println(person.GetDateOfBirth()) // 1989 | |
fmt.Println(person.getFoodStatus()) // No | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment