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

Time:03-26

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?

CodePudding user response:

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.

CodePudding user response:

I think this may help:

https://go.dev/play/p/M476VbaKn1c

type Foo struct{}

type Bar struct {
    Foo
}

func (f *Foo) protected() int {
    return 1
}

func (b *Bar) Try() int {
    return b.protected()
}
func main() {
    var b Bar
    fmt.Println(b.Try())
}
  •  Tags:  
  • go
  • Related