To implement custom pretty-printing functions for complex data structures in Go, you can follow these steps:
Step 1: Define a struct for your complex data structure Create a struct that represents your complex data structure. Include fields and nested structs as necessary.
Step 2: Implement the String()
method
Define a String()
method for your struct that returns a string representation of your complex data structure. This method will be called when you use fmt.Printf()
or fmt.Println()
.
Step 3: Use the fmt
package to format the output
Inside the String()
method, use the fmt.Sprintf()
function to format the output string. You can use the %v
verb to print the values of primitive types, and recursively call the String()
method for nested structs.
Step 4: Import the fmt
package and use the struct
Import the fmt
package in your Go file, and use fmt.Printf()
or fmt.Println()
to print your complex data structure. The String()
method will automatically be invoked.
Here's an example implementation for a complex data structure called Person
:
package main
import "fmt"
type Address struct {
Street string
City string
}
type Person struct {
Name string
Age int
Address Address
}
func (p Person) String() string {
return fmt.Sprintf("Name: %s, Age: %d, Address: %s", p.Name, p.Age, p.Address)
}
func main() {
p := Person{
Name: "John",
Age: 30,
Address: Address{
Street: "123 Main St",
City: "New York",
},
}
fmt.Println(p)
}
When you run this code, the String()
method will be invoked automatically, and the output will be:
Name: John, Age: 30, Address: {123 Main St New York}
You can customize the formatting in the fmt.Sprintf()
call as per your requirements to achieve the desired output format.