How To Not Keep Getters And Setters In Go

Example-1

type Foo interface {
Bar(…int) int
}
type foo struct {
x int
}

func (f *foo) Bar(x …int) int {
if len(x) == 1 {
f.x = x[0]
} else if len(x) > 1{
panic(“there can be only one”)
}
return f.x
}

Example-2

type Entity struct { ID uint64 Age uint64 }
type Human struct { Entity Name string }
func (e Entity) PrintAge() { fmt.Println(e.Age) }

func main()
{
entity := Entity{0, 20}
person := Person{Entity{1, 10}, “ojbway”}
entity.PrintAge()
person.PrintAge()
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s