你可以在Golang中编写一个接受多种类型作为参数的函数。

huangapple go评论102阅读模式
英文:

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

huangapple
  • 本文由 发表于 2016年4月23日 15:59:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/36808224.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定