Inherited struct and reflect MethodByName question?

528 views
Skip to first unread message

Nguyên Nguyễn Văn Cao

unread,
Oct 1, 2012, 7:29:32 AM10/1/12
to golan...@googlegroups.com
For example, I have:
 
type Foo struct{}
func (f *Foo) Call(name string) {
reflect.ValueOf(f).MethodByName(name).Call([]reflect.Value{})
}
func (f *Foo) A() {
fmt.Println("Foo A")
}

so I can use f.Call("A") to call method A. Now I have bar inherit from Foo
type Bar struct {
Foo
}
func (b *Bar) B() {
fmt.Println("Bar B")
}

Can anyway that I can use b.Call("B") to call B?

Thanks you!

Kevin Gillette

unread,
Oct 1, 2012, 7:48:57 AM10/1/12
to golan...@googlegroups.com
Go doesn't have inheritance; it has composition.

type Bar struct {
   Foo
}

means it has a field called Foo of type Foo, and that any "inheritance" you're thinking of is just syntactic sugar.

var b Bar
b.Call("B")

is syntactic sugar for:

b.Foo.Call("B")

Since Foo (the type) doesn't have a method called "B", this won't work. Even in most true object oriented languages this won't work (in those systems, you can only call methods in a child class that override methods in the parent). An embedded type will never be able to access the fields or methods of the type that embeds it, unless you provide a circular-reference field, but there's generally little benefit to doing this in real code.
Reply all
Reply to author
Forward
0 new messages