简体   繁体   English

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

[英]How do I write a function that accepts both string and int64 types in Go?

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. 我有message_id是字符串和id是主键。

I would like to accept both types for id parameter. 我想接受两种类型的id参数。

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 谢谢

Use interface{} like this working sample: 像下面的工作示例一样使用interface{}

package main

import "fmt"
import "errors"

func GetMessage(id interface{}) error {
    //fmt.Printf("v:%v\tT: %[1]T \n", 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM