Skip to content

Instantly share code, notes, and snippets.

@nikzayn
Last active June 15, 2022 13:28
Show Gist options
  • Save nikzayn/c3c96156a84355ffd84f9a90619b320c to your computer and use it in GitHub Desktop.
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
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
}
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