Go语言是否支持类似JS、Ruby的模板字符串?
Great question! Go doesn't have native support for string interpolation (template literals) like JavaScript's ${var} or Ruby's #{var} out of the box, but there are several solid alternatives to achieve the same result depending on your use case.
Here are the most common approaches:
1. Use fmt.Sprintf (Simple Variable Replacement)
This is the go-to method for basic string formatting and variable substitution. It uses placeholders like %s (for strings), %d (for integers), etc., to inject variables into your string.
package main import "fmt" func main() { name := "tom" sentence := fmt.Sprintf("My Name is %s", name) fmt.Println(sentence) // Output: My Name is tom }
It's lightweight, easy to read, and works with all basic data types—perfect for quick one-off string builds.
2. Use text/template or html/template (Complex Templates)
If you're dealing with more advanced scenarios (like generating HTML, configuration files, or multi-line templates with logic), Go's standard library has you covered with these template packages. They support variable substitution, conditionals, loops, and more.
For example, using text/template:
package main import ( "os" "text/template" ) func main() { name := "tom" const templateStr = "My Name is {{.Name}}" // Parse the template tmpl, err := template.New("nameTemplate").Parse(templateStr) if err != nil { panic(err) } // Execute the template with our data data := map[string]string{"Name": name} err = tmpl.Execute(os.Stdout, data) // Output: My Name is tom if err != nil { panic(err) } }
The html/template variant adds automatic HTML escaping to prevent injection attacks, making it ideal for web applications.
3. Use strings.Builder (High-Performance String Building)
If you need to concatenate many strings and variables efficiently (especially in loops or high-throughput code), strings.Builder is far more performant than using the + operator repeatedly.
package main import ( "fmt" "strings" ) func main() { name := "tom" var sb strings.Builder sb.WriteString("My Name is ") sb.WriteString(name) sentence := sb.String() fmt.Println(sentence) // Output: My Name is tom }
This method minimizes memory allocations, which is crucial for performance-critical code.
While Go doesn't have the concise syntax of JS or Ruby's template literals, these alternatives cover every common use case—pick the one that fits your needs best!
内容的提问来源于stack exchange,提问作者Ben Ammann

