Home > Backend Development > Golang > Go String Formatting: Beyond `fmt.Sprintf()` – What are the Alternatives?

Go String Formatting: Beyond `fmt.Sprintf()` – What are the Alternatives?

Susan Sarandon
Release: 2024-12-20 02:47:09
Original
641 people have browsed it

Go String Formatting:  Beyond `fmt.Sprintf()` – What are the Alternatives?

Equivalent of Python string.format in Go?

In Python, string interpolation using the format() method offers flexibility in ordering and replacing parameters. However, in Go, the fmt.Sprintf() function provides a more limited option, hindering internationalization (I18N). Is there a more suitable alternative that allows for independent parameter ordering?

Strings.Replacer

Utilizing strings.Replacer enables you to create your custom string formatter effectively.

func main() {
    file, err := "/data/test.txt", "file not found"

    log("File {file} had error {error}", "{file}", file, "{error}", err)
}

func log(format string, args ...string) {
    r := strings.NewReplacer(args...)
    fmt.Println(r.Replace(format))
}
Copy after login

Sample Output:

File /data/test.txt had error file not found
Copy after login

WiText/Template

The text/template package offers a template-based solution, though it can be more verbose than the Strings.Replacer approach.

type P map[string]interface{}

func main() {
    file, err := "/data/test.txt", 666

    log4("File {{.file}} has error {{.error}}", P{"file": file, "error": err})
}

func log4(format string, p P) {
    t := template.Must(template.New("").Parse(format))
    t.Execute(os.Stdout, p)
}
Copy after login

Sample Output:

File /data/test.txt has error 666
Copy after login

Explicit Argument Indices

fmt.Sprintf() supports explicit argument indices, allowing you to repeat the same index multiple times to substitute the same parameter. Learn more about this technique in the related question "Replace all variables in Sprintf with same variable."

The above is the detailed content of Go String Formatting: Beyond `fmt.Sprintf()` – What are the Alternatives?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template