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