Equivalent of Python string.format in Go?

前端 未结 6 1945
我在风中等你
我在风中等你 2020-12-02 17:18

In Python, you can do this:

\"File {file} had error {error}\".format(file=myfile, error=err)

or this:

\"File %(file)s had e         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 17:42

    I don't know of any easy way of naming the parameters, but you can easily change the order of the arguments, using explicit argument indexes:

    From docs:

    In Printf, Sprintf, and Fprintf, the default behavior is for each formatting verb to format successive arguments passed in the call. However, the notation [n] immediately before the verb indicates that the nth one-indexed argument is to be formatted instead. The same notation before a '*' for a width or precision selects the argument index holding the value. After processing a bracketed expression [n], subsequent verbs will use arguments n+1, n+2, etc. unless otherwise directed.

    Then you can, ie:

    fmt.Printf("File %[2]s had error %[1]s", err, myfile)
    

提交回复
热议问题