On Wednesday, 16 September 2020 at 10:51:27 UTC+2 stephan...@gmail.com wrote:
> Assume a public interface I with two methods NotInS and M whereas NotInS > is calling M. An implementation i of I which implements NotInS and M as > well as a specialization s of i which only implements M. Finally a > constructor whose return-type is I returns a pointer to an instance of > s. Calling on this return-value NotInS will execute i.M() as the > following test shows. I would like it to call s.M(). How would I do > this in a goish way? Thanks for any help! > Well, start of by not using Java/C#/C++ terminology as Go is different and in Go you simply cannot have a "specialization s of i" as there are no "specialization" as there is no inheritance. Also let's rewrite the code to be a bit more Go'ish: package main import "fmt" type I interface { NotInS() M() } type T struct{} func (t *T) NotInS() { t.M() } func (t *T) M() { fmt.Println("T.M") } type S struct{ *T } func (s *S) M() { fmt.Println("S.M") } func main() { x := &S{&T{}} x.NotInS() } You see S has no method NotInS defined and all calls to NotInS are automatically directed to implicit field T of S. Remember that embedding a *T in an S has nothing to do with inheritance or specialisation. It is just some tiny syntactic sugar for an implicit field and automatic method forwarding to that field. Spelling it out your code is equivalent to: type S struct{ T *T } func (s *S) NotInS() { s.T.M() } The embedded T doesn't know it is a field of S and you call T's M method and it is simply impossible to have S's M method called like this. You must redesign. Embedding is not inheritance and you cannot modle inheritance based design with embedding no matter how hard you try. V. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/27f6fcb8-2040-491a-8309-85629d02406bn%40googlegroups.com.