英文:
How can I write a function in Golang which takes multiple types as a parameter?
问题
我正在尝试在Golang中编写一个函数,该函数将序列化一个map和一个slice(将其转换为字符串)。我希望它只接受一个参数,但我不确定如何使其只接受map和slice。我知道可以使用类似下面的函数,但在此之后我感到困惑。我仍在努力理解接口的概念。
func Serialize(data interface{}) string {
return ""
}
如果不需要创建自己的结构体,那将是最好的。非常感谢您能解释一下如何使这个Serialize函数接受map和结构体。
英文:
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.
答案1
得分: 0
你可以简单地使用fmt.Sprintf
来实现这个功能:
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
}
这将输出:
[a b c]
map[b:b a:a]
{x 7}
如果需要的话,你可以使用strings.TrimSuffix
和strings.TrimPrefix
轻松去掉{}
、[]
和map[]
。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论