如何在Golang中编写一个以多种类型为参数的函数?
I am trying to write a function in Golang which will serialize a map and a slice (convert it to a string). I want it to take one parameter but I am unsure of how to make it accept a map and a slice only. I know I can use something like the following function but beyond this point I am confused. I am still trying to wrap my head around interfaces.
func Serialize(data interface{}) string {
return ""
}
It is preferred if I don't need to create my own struct for it. An explanation of how I could allow this Serialize function to accept maps and structs would be hugely appreciated.
我正在尝试用Golang写一个函数,该函数将序列化地图和切片(将其转换为字符串) 。 我希望它采用一个参数,但是我不确定如何使它仅接受地图和切片。 我知道我可以使用类似以下功能的东西,但在这一点上我感到困惑。 我仍在尝试绕过接口。 p>
func Serialize(data interface {})string {
return“”
}
code>
如果我不需要为其创建自己的结构,则它是首选。 非常感谢我对如何允许此Serialize函数接受映射和结构的解释。 p>
div>
You could simply use fmt.Sprintf
for this:
type foo struct {
bar string
more int
}
func main() {
s := []string{"a", "b", "c"}
fmt.Println(Serialize(s))
m := map[string]string{"a": "a", "b": "b"}
fmt.Println(Serialize(m))
t := foo{"x", 7}
fmt.Println(Serialize(t))
}
func Serialize(data interface{}) string {
str := fmt.Sprintf("%v", data)
return str
}
This will print:
[a b c]
map[b:b a:a]
{x 7}
You can easily trim off the {}
, []
and map[]
if desired/required with strings.TrimSuffix
and strings.TrimPrefix