douchensi8625 2016-08-06 07:06
浏览 95
已采纳

如何在Go中编写一个同时接受字符串和int64类型的函数?

I have function that looks like this

func GetMessage(id string, by string) error {
    // mysql query goes here
}

I have message_id which is string and id which is primary key.

I would like to accept both types for id parameter.

I have tried like this

if (by == "id") {
        int_id, err := strconv.ParseInt(id, 10, 64)
        if err != nil {
            panic(err)
        }
        id = int_id
    }

But I'm getting error like

cannot use int_id (type int64) as type string in assignment

can someone help me?

Thanks

  • 写回答

1条回答 默认 最新

  • dousong9729 2016-08-06 07:20
    关注

    Use interface{} like this working sample:

    package main
    
    import "fmt"
    import "errors"
    
    func GetMessage(id interface{}) error {
        //fmt.Printf("v:%v\tT: %[1]T 
    ", id)
        switch v := id.(type) {
        case string:
            fmt.Println("Hello " + v)
        case int64:
            fmt.Println(v + 101)
        default:
            //panic("Unknown type: id.")
            return errors.New("Unknown type: id.")
        }
        return nil
    }
    
    func main() {
        message_id := "World"
        id := int64(101)
        GetMessage(message_id)
        GetMessage(id)
    }
    

    output:

    Hello World
    202
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据