Golang通用参数 [英] Golang generic param
本文介绍了Golang通用参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种方法可以通过通用参数使用一个函数,而不是如下所示具有两个函数?我有Java背景,正在寻找一种具有这样的功能
Is there a way to use one function using a generic parameter instead of having two functions as shown below? I have Java background and looking for a way to have something like this
//Java
public Something doSomething(T val)
//Go
func (l *myclass) DoSomethingString(value string) error {
test := []byte[value]
// do something with test
return err
}
func (l *myclass) DoSomethingInt(value int64) error {
test := []byte[value]
// do something with test
return err
}
推荐答案
不幸的是,Go没有泛型,也没有重载.您可以使用类型为 interface {}
的参数并将其切换为实型:
Unfortunately, Go has no generics and no overloading. You can use a parameter of type interface{}
and switch over it's real type:
func (*Test) DoSomething(p interface{}) {
switch v := p.(type) {
case int64:
fmt.Println("Got an int:", v)
case string:
fmt.Println("Got a string", v)
default:
fmt.Println("Got something unexpected")
}
}
这篇关于Golang通用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文