How to convert interface{} to string?

前端 未结 3 879
暖寄归人
暖寄归人 2021-01-30 07:38

I\'m using docopt to parse command-line arguments. This works, and it results in a map, such as

map[:www.google.de :80 --help:false --ver         


        
3条回答
  •  离开以前
    2021-01-30 08:18

    To expand on what Peter said: Since you are looking to go from interface{} to string, type assertion will lead to headaches since you need to account for multiple incoming types. You'll have to assert each type possible and verify it is that type before using it.

    Using fmt.Sprintf (https://golang.org/pkg/fmt/#Sprintf) automatically handles the interface conversion. Since you know your desired output type is always a string, Sprintf will handle whatever type is behind the interface without a bunch of extra code on your behalf.

提交回复
热议问题