In Go, to print struct variables in the console, you can use the Println or Printf functions from the fmt package. Additionally, for a more readable output of struct contents, you can use the %+v format specifier, which outputs struct information with field names and corresponding values. If you need full control over the output format, you might implement the String() method to customize the string representation. Here is a simple example:
First, define a struct:
gopackage main import ( "fmt" ) // Define an example struct type Person struct { Name string Age int City string }
Then, create a struct instance and print it:
gofunc main() { // Create a struct instance p := Person{ Name: "Alice", Age: 25, City: "New York", } // Use the fmt package to print the struct // %+v prints struct information with field names and values fmt.Printf("Person: %+v\n", p) // Alternatively, using fmt.Println prints the struct's values without field names fmt.Println("Person:", p) // For more customized output, implement the String method fmt.Println(p.String()) } // Implement the String method to customize the string representation of Person func (p Person) String() string { return fmt.Sprintf("Name: %s, Age: %d, City: %s", p.Name, p.Age, p.City) }
When you run this code, the console will output:
shellPerson: {Name:Alice Age:25 City:New York} Person: {Alice 25 New York} Name: Alice, Age: 25, City: New York
In the first Printf, the %+v format specifier prints each field name and its corresponding value. When using Println, only the struct's values are printed without field names. Finally, by implementing the String() method, you achieve a fully customized output format.