This is how embedding works, there's nothing you can do about it. (Actually there is, see dirty trick at the end.)
What you want may be achieved with interfaces though. Make your structs unexported, (B
=> b
and C
=> c
), and create "constructor" like functions, which return interface types, containing only the methods you wish to publish:
type b struct {
A
}
type c struct {
A
}
type Helloer interface {
Hello()
}
type HelloWorlder interface {
Helloer
World()
}
func NewB() Helloer {
return &b{}
}
func NewC() HelloWorlder {
return &c{}
}
You might want to call the interfaces and functions different, this is just for demonstration.
Also note that while the returned Helloer
interface does not include the World()
method, it is still possible to "reach" it using type assertion, e.g.:
h := NewB() // h is of type Helloer
if hw, ok := h.(HelloWorlder); ok {
hw.World() // This will succeed with the above implementations
}
Try this on the Go Playground.
Dirty trick
If a type embeds the type A
, (fields and) methods of A
that get promoted will become part of the method set of the embedder type (and thus become methods of type A
). This is detailed in Spec: Struct types:
A field or method f
of an anonymous field in a struct x
is called promoted if x.f
is a legal selector that denotes that field or method f
.
The focus is on the promotion, for which the selector must be legal. Spec: Selectors describes how x.f
is resolved:
The following rules apply to selectors:
- For a value
x
of type T
or *T
where T
is not a pointer or interface type, x.f
denotes the field or method at the shallowest depth in T
where there is such an f
. If there is not exactly one f
with shallowest depth, the selector expression is illegal.
[...]
What does this mean? Simply by embedding, B.World
will denote the B.A.World
method as that is at the shallowest depth. But if we can achieve so that B.A.World
won't be the shallowest, the type B
won't have this World()
method, because B.A.World
won't get promoted.
How can we achieve that? We may add a field with name World
:
type B struct {
A
World int
}
This B
type (or rather *B
) will not have a World()
method, as B.World
denotes the field and not B.A.World
as the former is at the shallowest depth. Try this on the Go Playground.
Again, this does not prevent anyone to explicitly refer to B.A.World()
, so that method can be "reached" and called, all we achieved is that the type B
or *B
does not have a World()
method.
Another variant of this "dirty trick" is to exploit the end of the first rule: "If there is not exactly one f
with shallowest depth". This can be achieved to also embed another type, another struct which also has a World
field or method, e.g.:
type hideWorld struct{ World int }
type B struct {
A
hideWorld
}
Try this variant on the Go Playground.