Go

如何在Golang中编写函数来处理两种类型的输入数据

发布于 2021-02-01 11:03:08

我有多个struct共享某些字段。例如,

type A struct {
    Color string
    Mass  float
    // ... other properties
}
type B struct {
    Color string
    Mass  float
    // ... other properties
}

我还有一个仅处理共享字段的功能,例如

func f(x){
    x.Color
    x.Mass
}

如何处理这种情况?我知道我们可以将颜色和质量转换为函数,然后可以使用interface并将该接口传递给function
f。但是,如果不能更改A和的类型,该怎么办B。我是否必须定义两个具有基本相同实现的功能?

关注者
0
被浏览
61
1 个回答
  • 面试哥
    面试哥 2021-02-01
    为面试而生,有面试问题,就找面试哥。

    在Go中,您不会像Java,c#等那样使用传统的多态性。大多数事情都是使用合成和类型嵌入完成的。一种简单的方法是更改​​设计并将公用字段分组到单独的结构中。这只是一种不同的想法。

    type Common struct {
        Color string
        Mass  float32
    }
    type A struct {
        Common
        // ... other properties
    }
    type B struct {
        Common
        // ... other properties
    }
    
    func f(x Common){
        print(x.Color)
        print(x.Mass)
    }
    
    //example calls
    func main() {
        f(Common{})
        f(A{}.Common)
        f(B{}.Common)
    }
    

    使用此处)提到的接口和获取器也有其他方法,但是IMO这是最简单的方法



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看