【问题标题】:How do I write a function that accepts both string and int64 types in Go?如何在 Go 中编写一个同时接受 string 和 int64 类型的函数?
【发布时间】:2016-12-12 14:17:42
【问题描述】:

我有这样的功能

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

我有message_id 是字符串,id 是主键。

我想接受这两种类型的 id 参数。

我试过这样

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

但是我遇到了类似的错误

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

有人可以帮我吗?

谢谢

【问题讨论】:

  • 错误的原因,是因为你的函数只接受字符串,所以你为什么要转换id?你可以直接将它传递给你的函数。
  • 我需要将它作为 mysql where 子句的 int 传递。这就是为什么我要转换 id

标签: go types


【解决方案1】:

像这个工作示例一样使用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)
}

输出:

Hello World
202

【讨论】:

  • 非常感谢。这很有帮助
猜你喜欢
  • 2016-07-07
  • 1970-01-01
  • 2021-11-25
  • 2011-02-24
  • 1970-01-01
  • 1970-01-01
  • 2012-09-08
  • 2014-11-28
  • 2019-07-31
相关资源
最近更新 更多