该方法是否应该与接口的签名显式地收缩?

时间:2019-03-08 03:30:38

标签: go

我是golang的新手,我不太了解为什么以下演示程序可以成功执行,

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)
}

该接口希望返回三个值,但是方法getAge仅返回两个值,但仍然有效。如何理解golang中的这种行为?

谢谢!

1 个答案:

答案 0 :(得分:2)

Foo未实现fake。如果您稍微扩展一下代码示例(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)
}

这会产生一个描述性很强的编译错误:

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)