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