Introduction to String Interpolation in Go
String interpolation is a common practice in many programming languages where variables are embedded into strings. However, in Go, the string interpolation as seen in some languages like Python with f-strings isn't directly available. Instead, Go uses formatted I/O similar to C with the fmt package.
Basic String Formatting
The fmt package in Go provides a variety of functions to format strings with placeholders.
package main
import "fmt"
func main() {
name := "Alice"
age := 30
formattedString := fmt.Sprintf("My name is %s and I am %d years old.", name, age)
fmt.Println(formattedString)
}
In this snippet, fmt.Sprintf is used with format specifiers like %s for strings and %d for integers to format our string. It returns a formatted string that can be printed or used elsewhere in the code.
Intermediate Usage of Strings with Complex Structures
Go's format verbs allow you to interpolate various data types including floats, characters, and strings. Here's how you can work with more complex data types.
package main
import "fmt"
func main() {
person := struct {
Name string
Age int
Height float64
}{"Bob", 25, 5.9}
formattedString := fmt.Sprintf("Name: %s, Age: %d, Height: %.1f", person.Name, person.Age, person.Height)
fmt.Println(formattedString)
}
Here, the struct holds the person's attributes, and the format specifier %.1f ensures that the height is printed with one decimal place.
Advanced String Truncation and Alignment
Advanced usage of Go's formatting functions includes string truncation and alignment. Here’s an example for table-like formatting and fixed width output.
package main
import "fmt"
func main() {
people := []struct {
Name string
Age int
Occupation string
}{
{"Charlie", 28, "Engineer"},
{"Dana", 35, "Painter"},
{"Edward", 22, "Student"},
}
fmt.Printf("%-10s | %-3s | %-10s\n", "Name", "Age", "Occupation")
fmt.Println(strings.Repeat("-", 30))
for _, person := range people {
fmt.Printf("%-10s | %-3d | %-10s\n", person.Name, person.Age, person.Occupation)
}
}
In this code, the %-10s and %-3d format specifiers are used to left align strings and numbers and ensure they occupy a fixed width, creating a table-like view of the data which comes in handy for pretty-printing.
Template Usage in Go
Another powerful way to manage string interpolation and creation in Go is through templates. The text/template package provides data-driven templates for generating formatted output.
Basic Template Example
Start with defining a template and parsing it:
package main
import (
"os"
"text/template"
)
func main() {
tmpl, err := template.New("test").Parse("Hello, my name is {{.Name}} and I am {{.Age}} years old.")
if err != nil {
panic(err)
}
person := map[string]interface{}{"Name": "Frank", "Age": 40}
tmpl.Execute(os.Stdout, person)
}
In this example, a simple template is parsed and executed with a map as data, outputting the values corresponding to .Name and .Age.
Using Structs with Templates
Templates can be used with more structured data like structs:
package main
import (
"os"
"text/template"
)
func main() {
type Person struct {
Name string
Age int
}
person := Person{"Grace", 33}
tmpl, err := template.New("structExample").Parse("{{.Name}} is {{.Age}} years old.")
if err != nil {
panic(err)
}
tmpl.Execute(os.Stdout, person)
}
Here, the struct Person is directly used with the template, providing a neat way to generate complex text outputs based on data.
Looping in Templates
Templates in Go can also iterate over slices or maps:
package main
import (
"os"
"text/template"
)
func main() {
people := []map[string]interface{}{
{"Name": "Hannah", "Occupation": "Doctor"},
{"Name": "Ivy", "Occupation": "Pilot"},
}
tmplText := {{/* Multi-line template string */}}`{{range .}}{{.Name}} is a {{.Occupation}}.
{{end}}`
tmpl, err := template.New("loopExample").Parse(tmplText)
if err != nil {
panic(err)
}
tmpl.Execute(os.Stdout, people)
}
This example displays a list of names and their occupations, iterating over a slice. Templates are very flexible for generating formatted output without direct string manipulation.