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)) }
Sample Output:
File /data/test.txt had error file not found
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) }
Sample Output:
File /data/test.txt has error 666
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!