How to convert interface{} to string?

前端 未结 3 877
暖寄归人
暖寄归人 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.

    0 讨论(0)
  • 2021-01-30 08:19

    You don't need to use a type assertion, instead just use the %v format specifier with Sprintf:

    hostAndPort := fmt.Sprintf("%v:%v", arguments["<host>"], arguments["<port>"])
    
    0 讨论(0)
  • 2021-01-30 08:31

    You need to add type assertion .(string). It is necessary because the map is of type map[string]interface{}:

    host := arguments["<host>"].(string) + ":" + arguments["<port>"].(string)
    

    Latest version of Docopt returns Opts object that has methods for conversion:

    host, err := arguments.String("<host>")
    port, err := arguments.String("<port>")
    host_port := host + ":" + port
    
    0 讨论(0)
提交回复
热议问题