如何在Golang中编写函数来处理两种类型的输入数据 [英] how to write a function to process two types of input data in golang

查看:104
本文介绍了如何在Golang中编写函数来处理两种类型的输入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个struct共享一些字段.例如

I have multiple structs share some fields. For example,

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

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

I also have a function that only deals with the shared fields, say

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

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

How to deal with such situations? I know we can turn the color and mass into functions, then we can use interface and pass that interface to the function f. But what if the types of A and B cannot be changed. Do I have to define two functions with essentially the same implementation?

推荐答案

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

In Go you don't the traditional polymorphism like in Java, c#, etc. Most thing are done using composition and type embedding. A way of doing this simply is by changing your design and group the common field in a separate struct. It's just a different of thinking.

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这就是最简单的方法

There are other ways too by using interfaces and getters mentioned here but IMO this is the simplest way

这篇关于如何在Golang中编写函数来处理两种类型的输入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆