首页 > 解决方案 > 如何将具有返回更广泛接口的方法的 interfaceA 类型的变量分配给具有更窄返回的 interfaceB 类型的变量

问题描述

第一次在这里发问题,如果格式错误,请见谅。请让我知道如何改进我的提问。

package main

type smallerInterface interface {
    Problem() smallerRet
}

type biggerInterface interface {
    Problem() biggerRet
}

type smallerRet interface {
    Wait() bool
}

type biggerRet interface {
    Wait() bool
    Error() error
}

type ret struct{}

type sample struct{}

func (ret) Wait() bool {
    return true
}

func (ret) Error() error {
    return nil
}

func (sample) Problem() biggerRet {
    return ret{}
}
    

func main() {
    var first biggerInterface = sample{}
    var second smallerInterface = sample{}
}

问题的演示可以在这里查看https://play.golang.org/p/l0xdO03bBy7

基本上,有没有办法调和两者smallerInterfacebiggerInterface因此sample可以分配给类型的变量smallerInterface

具体来说,我想smallerInterface在内部测试中用于模拟,并biggerInterface从 producton 的外部库中接收。因此,最好保留smallerRet接口,这样我就可以保持模拟返回值接口很小,样本是生产返回值。

此外,这个问题或概念是否有名称?

提前致谢!

标签: gointerfacereturn-type

解决方案


您可以尝试嵌入接口,以便可以将示例分配给 type smallerInterface。我重新创建了您的代码,如下所示:

package main

import "fmt"

type smallerInterface interface {
    biggerInterface
}

type biggerInterface interface {
    Problem() biggerRet
}

type smallerRet interface {
    Wait() bool
}

type biggerRet interface {
    Wait() bool
    Error() error
}

type ret struct{}

type sample struct{}

func (ret) Wait() bool {
    return true
}

func (ret) Error() error {
    return nil
}

func (sample) Problem() biggerRet {
    return ret{}
}

func main() {
    var first biggerInterface = sample{}
    var second smallerInterface = sample{}

    fmt.Println(first)
    fmt.Println(second)
}

输出:

{}
{}

推荐阅读