登录
首页 >  Golang >  Go问答

用Golang,结构体方法可以接受不同类型的多个参数

来源:stackoverflow

时间:2024-02-07 22:45:22 236浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《用Golang,结构体方法可以接受不同类型的多个参数》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我的方法如下:

func (t *worker) updateinfo(n structtype1, node structtype2)

但是,现在我需要使用这个api来处理structtype1和structtype3。这意味着 n 可以是 structtype3。

我如何修改方法来实现此目的,而不是编写如下所示的另一个方法并重复相同的代码?

func (t *Worker) updateInfo(n structType3, node structType2)

编辑:这些结构都是我自己自定义的结构


正确答案


在这种情况下,您可以使用泛型

例如,假设 structtype1structtype2 有一个名为 print 的方法。

type  structtype1 struct {}
func(st1 structtype1) print() {
 fmt.println("calling print function of structtype1")
}

type  structtype3 struct {}
func(st3 structtype3) print() {
 fmt.println("calling print function of structtype2")
}

我们可以定义一个接口类型声明,如下所示。

type struct13 interface {
 print()
 structtype1 | structtype3 // type union 
}

然后您需要使用类型参数修改 worker 结构体和 updateinfo 函数。 (注:struct13 中的 print 函数用于演示目的。)

type worker[t struct13] struct{}

func (t *worker[t]) updateinfo(n t, node structtype2) {
 n.print()
}

我们可以使用上面的实现,如下所示。

    st1 := structType1{}
    st2 := structType2{}
    st3 := structType3{}


    w1 := Worker[structType1]{}
    w1.updateInfo(st1,st2)

    w2 := Worker[structType3]{}
    w2.updateInfo(st3,st2)

到这里,我们也就讲完了《用Golang,结构体方法可以接受不同类型的多个参数》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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