登录
首页 >  Golang >  Go问答

同一方法的多个实现可能与 Go 和接口有不同的依赖关系

来源:stackoverflow

时间:2024-04-21 18:48:38 402浏览 收藏

大家好,今天本人给大家带来文章《同一方法的多个实现可能与 Go 和接口有不同的依赖关系》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我在使用界面时遇到问题。

我有一个 compute(a, b int) 方法,它有 2 个实现,具体取决于接收器。

func (addition *addition) compute(a, b int) int{
    return a+b
}

func (mult *multiplication) compute(a, b int) int{
    return a*b
}


type myinterface{
    compute(a, b int) int
}

假设我需要在乘法中调用 webservice 来获取 a 的值。

现在我们有:

func (mult *multiplication) compute(iface wsinterface, a, b int) int{
    a := iface.geta()
    return a*b
}

现在,我需要将 iface wsinterface 添加到 compute() 接口定义中,并将其添加到 addition 中,即使它不需要它。

我将以:

结束
type Addition struct{}

type Multiplication struct{}


func main() {
    addition := &Addition{}
    multiplication := &Multiplication{}
    res1 := addition.Compute(nil, 1, 2)
    res2 := addition.Compute(multiplication, 3, 4)
    fmt.Print(res1, res2)
}

type WSInterface interface {
    getA() int
}

func (mult *Multiplication) getA() int {
    return 1 // Mocked
}

type myInterface interface {
    Compute(iface myInterface, a, b int) int
}

func (addition *Addition) Compute(iface WSInterface, a, b int) int {
    return a + b
}

func (mult *Multiplication) Compute(iface WSInterface, a, b int) int {
    return iface.getA() * b
}

但除此之外,它不会被使用。

在现实生活中,您可以对不同的微服务有多个依赖项,并且我发现定义不会在函数中使用的参数并不是那么优雅。这里肯定有什么问题。

这样做可以吗?这是一个不好的模式吗?或者我应该如何修复它?


解决方案


这些特殊的接口/对象应该在构造函数中传递,保持接口本身的干净。

类似于:

type multiplication struct {
  iface otherinferface
  // .. other multiplication-specific fields
}

func newmultiplication(iface otherinterface) *multiplication {
  return &multiplication{iface: iface}
}

然后:

func (mult *multiplication) compute(a, b int) int{
    a := mult.iface.geta()
    return a*b
}

因此您的 myinterface 仍然简单干净:

type myInterface interface {
  Compute(a, b int)
}

到这里,我们也就讲完了《同一方法的多个实现可能与 Go 和接口有不同的依赖关系》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>