Equivalent of Python string.format in Go?

前端 未结 6 1944
我在风中等你
我在风中等你 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 17:58

    You can try the Go Formatter library that implements replacement fields surrounded by curly braces {} format strings similar to Python format.

    Working code example Go Playground:

    package main
    
    import (
        "fmt"
    
        "gitlab.com/tymonx/go-formatter/formatter"
    )
    
    func main() {
        formatted, err := formatter.Format("Named placeholders {file}:{line}:{function}():", formatter.Named{
            "line":     3,
            "function": "func1",
            "file":     "dir/file",
        })
    
        if err != nil {
            panic(err)
        }
    
        fmt.Println(formatted)
    }
    

    Output:

    Named placeholders dir/file:3:func1():
    

提交回复
热议问题