Encapsulation in Go


(Raja Pandian) #1

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

Thanks,
Rajapandian.B


(Sandertv) #2

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
}

(Raja Pandian) #3

Thanks


(system) #4

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