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 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)