To conditionally format and print data based on specific criteria in Go, you can use the text/template
package. Follow these steps:
type Employee struct {
Name string
Age int
}
if
statement and access the fields of the data structure using the dot notation. For instance, let's create a template to print only the names of employees who are older than 30:const templateString = `
{{range .}}
{{if gt .Age 30}}
{{.Name}}
{{end}}
{{end}}
`
template.Parse
function:template, err := template.New("employeeTemplate").Parse(templateString)
if err != nil {
log.Fatal(err)
}
employees := []Employee{
{Name: "John", Age: 25},
{Name: "Alice", Age: 35},
{Name: "Peter", Age: 40},
}
err = template.Execute(os.Stdout, employees)
if err != nil {
log.Fatal(err)
}
This will print the names of employees who are older than 30:
Alice
Peter
You can modify the template and the conditions to suit your specific needs.