How to conditionally format and print data based on specific criteria in Go?

To conditionally format and print data based on specific criteria in Go, you can use the text/template package. Follow these steps:

  1. Define a data structure that represents the data you want to format and print. For example, let's say you have a list of employees with their names and ages:
type Employee struct { Name string Age int }
  1. Create a template that specifies the formatting rules and conditions. You can embed conditional logic using the 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}} `
  1. Parse the template using the template.Parse function:
template, err := template.New("employeeTemplate").Parse(templateString) if err != nil { log.Fatal(err) }
  1. Prepare the data that you want to format and print. For example, create a slice of employees:
employees := []Employee{ {Name: "John", Age: 25}, {Name: "Alice", Age: 35}, {Name: "Peter", Age: 40}, }
  1. Execute the template, passing the data to it:
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.