duanshan5259 2016-04-23 07:59
浏览 593
已采纳

如何在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.

  • 写回答

1条回答 默认 最新

  • dtj4307 2016-04-23 08:30
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?