'Is there a 'protected' analog in golang for accessing an embded structs private methods?

In Java/C++ you can use the 'protected' to make private methods/attributes of base classes accessible from inherited classes. I noticed in Go there doesn't seem to be anything similar.

If that's the case, what's the standard practice in Go for when you might want to access an embedded types private methods?

More specifically:

I have a package called package1, there's a method called setUpPackage1() to setup package1 - (setUpPackage1() is intentionally unreported because package1 is never intended to be used as is, it's indented to be used as a base to be extended upon)

I then make a separate package package2 - which has a struct called package2 that has package1 embedded in it.

I want to create a method called NewPackage2(). I want to call package1.setUpPackage1() inside NewPackage2().

Is there any way Go will allow something like this, and if not, what's the Go way?

go


Solution 1:[1]

Use unexported method.

In Go, a name is unexported if it begins with a lowercase letter, which means you can not access the unexported method from other packages ("private" to other packages). So keep the type with unexported method and code using it in the same package, you can still use the method inside. This effect is similar to "protected" in C++, IMHO.

Solution 2:[2]

A package is the smallest unit of private encapsulation in Go.

If you really need a bigger level of control, you can define a public SetupPackage1 and define the package 1 as internal to restrict access.

https://dave.cheney.net/2019/10/06/use-internal-packages-to-reduce-your-public-api-surface

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rustyhu
Solution 2