Method 1: Printf with Formatting

One of the simplest ways to print the variables of a struct is to use the fmt.Printf function along with format specifiers. This method allows you to control the format of the output.

Here’s an example of how you can print a struct’s variables using Printf:

package main

import (
    "fmt"
)

type Person struct {
    FirstName string
    LastName  string
    Age       int
}

func main() {
    person := Person{
        FirstName: "John",
        LastName:  "Doe",
        Age:       30,
    }

    fmt.Printf("Name: %s %s\n", person.FirstName, person.LastName)
    fmt.Printf("Age: %d\n", person.Age)
}

In this example, we define a Person struct and use Printf to print the individual fields with appropriate formatting.

OUTPUT:
Name: John Doe
Age: 30

Method 2: %+v for Structs

Go’s fmt package provides a convenient %+v format verb specifically designed for printing structs. It prints the struct’s field names along with their values.

package main

import (
    "fmt"
)

type Person struct {
    FirstName string
    LastName  string
    Age       int
}

func main() {
    person := Person{
        FirstName: "John",
        LastName:  "Doe",
        Age:       30,
    }

    fmt.Printf("%+v\n", person)
}

Using %+v simplifies the process and is especially useful for debugging because it displays both field names and values.

OUTPUT:
{FirstName:John LastName:Doe Age:30}

Method 3: Spew for Complex Structs

When working with complex structs or deeply nested data structures, the github.com/davecgh/go-spew/spew package can be incredibly helpful. It provides a more detailed and readable representation of complex data.

First, you need to install the package using go get github.com/davecgh/go-spew/spew. Then, you can use it to print structs like this:

package main

import (
    "github.com/davecgh/go-spew/spew"
)

type Person struct {
    FirstName string
    LastName  string
    Age       int
}

func main() {
    person := Person{
        FirstName: "John",
        LastName:  "Doe",
        Age:       30,
    }

    spew.Dump(person)
}

OUTPUT:

(main.Person) {
FirstName: (string) (len=4) “John”,
LastName: (string) (len=3) “Doe”,
Age: (int) 30
}

Using spew is especially beneficial when dealing with complex data structures, as it provides a detailed representation, including nested fields and their values.

Conclusion

Printing struct variables in the console in Go is a common task when debugging or logging information about your program’s data. The methods described in this blog post, whether using Printf, %+v formatting, or the spew package, offer various options for displaying struct fields based on your specific needs. Choose the one that best suits your requirements for readability and debugging convenience.

Support On Demand!

                                         
Golang