I am new with the golang, I am not quite understand why the below demo program could be executed successfully,
type fake interface {
getAge(valueInt int, valStr string) (age int, name string, err error)
}
type Foo struct {
name string
}
func (b *Foo) getAge(valueInt int, valStr string) (age int, retErr error) {
age = valueInt
return age, nil
}
func main() {
inst := &Foo{name:"foo"}
value, _ := inst.getAge(2, "foo")
fmt.Println(value)
}
The interface wants to return three value, but the method getAge
only return two, but it still works. How to understand this behavior in golang?
Thanks!
Foo
doesn't implement fake
. This is apparent if you extend your code sample a bit (try it on the Go playground):
package main
import "fmt"
type fake interface {
getAge(valueInt int, valStr string) (age int, name string, err error)
}
type Foo struct {
name string
}
func (b *Foo) getAge(valueInt int, valStr string) (age int, retErr error) {
age = valueInt
return age, nil
}
func bar(f fake) {
_, name, _ := f.getAge(10, "")
}
func main() {
inst := &Foo{name: "foo"}
value, _ := inst.getAge(2, "foo")
fmt.Println(value)
bar(inst)
}
This produces a compile error that's pretty descriptive:
prog.go:28:5: cannot use inst (type *Foo) as type fake in argument to bar:
*Foo does not implement fake (wrong type for getAge method)
have getAge(int, string) (int, error)
want getAge(int, string) (int, string, error)