go - 如何将具有返回更广泛接口的方法的 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
基本上,有没有办法调和两者smallerInterface
,biggerInterface
因此sample
可以分配给类型的变量smallerInterface
?
具体来说,我想smallerInterface
在内部测试中用于模拟,并biggerInterface
从 producton 的外部库中接收。因此,最好保留smallerRet
接口,这样我就可以保持模拟返回值接口很小,样本是生产返回值。
此外,这个问题或概念是否有名称?
提前致谢!
解决方案
您可以尝试嵌入接口,以便可以将示例分配给 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)
}
输出:
{}
{}
推荐阅读
- azure-pipelines - Azure 数据工厂简单数据流失败
- angular - 我可以扩展“验证器”命名空间以包含我的自定义验证器实现吗?
- javascript - 单击表格角度中的删除按钮后刷新页面
- python - 尽管客户端失去了网络连接,BaseHTTPServer 仍在写入
- javascript - 如何将复选框值传递给 Python Flask 的模式引导程序从 mysql 表中删除数据?
- mysql - 如何在 Mybatis 中使用 param #{} 连接别名字段
- javascript - 是的,正则表达式 Instagram 主题标签
- c++ - 无法在 C++ 中包含头文件
- mysql - 具有多个自动增量的列
- python - 如何使用 venv 插件安装 pyenv 下载?