Encapsulation in Go

Hi,
How to implement Encapsulation in Go Lang? Any basic examples with explanation.

Thanks,
Rajapandian.B

I’m not entirely sure what you mean by encapsulation, but if you’re referring to ‘protecting’ properties from other parties and having methods that operate on them instead, this would probably be the simplest example:

type A struct {
  b string // b is unexported. It is not accessible outside of this package.
}

func (a *A) B() string { // It is usually convention to call such getters the same as their unexported property, except exported.
  return a.b
}

func (a *A) SetB(b string) {
  a.b = b
}
1 Like

Thanks

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.