dongyong5912 2016-08-28 05:45
浏览 50

Golang通用参数

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
}
  • 写回答

1条回答 默认 最新

  • dqqg0811 2016-08-28 05:55
    关注

    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")
        }
    }
    

    Link on Playground

    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题的应用
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办