Sobes.tech
Junior — Middle

Is it possible to declare methods with private visibility in Go?

sobes.tech AI

Answer from AI

In Go, the scope of methods is determined by the case of the first letter of the method name. If the method name starts with an uppercase letter, it is exported (public); if it starts with a lowercase letter, the method is private (accessible only within the package). Thus, in Go, there is no keyword private, but you can declare a method with private scope simply by starting its name with a lowercase letter.

Example:

package mypackage

type MyStruct struct {}

func (m MyStruct) publicMethod() {
    // private method, accessible only within the mypackage package
}

func (m MyStruct) PublicMethod() {
    // public method, accessible from other packages
}

Calling publicMethod will only be possible within the mypackage package.

Is it possible to declare methods with private… - sobes.tech