👣 Print struct variables in Go

introduction strings go-spew

Standard fmt.Print() does not print variable names of Go structs, but it does not mean you cannot do that. To print struct variables in Go, you can use the following methods:

See the example below and compare these three options.

package main

import (
    "encoding/json"
    "fmt"
    "log"

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

type Fruit struct {
    Name    string
    color   string
    Similar *Fruit
}

func main() {
    strawberry := Fruit{
        Name:    "strawberry",
        color:   "red",
        Similar: nil,
    }

    raspberry := Fruit{
        Name:    "raspberry",
        color:   "pink",
        Similar: &strawberry,
    }

    // fmt.Printf with format verbs
    fmt.Printf("fmt.Printf with format verbs\n")
    fmt.Printf("%+v\n%#v\n", raspberry, raspberry)

    // json encoding
    fmt.Printf("---\njson encoding\n")
    jsonData, err := json.Marshal(&raspberry)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(jsonData))

    // go-spew
    fmt.Printf("---\ngo-spew\n")
    spew.Dump(raspberry)
}

Output:

fmt.Printf with format verbs
{Name:raspberry color:pink Similar:0xc000070390}
main.Fruit{Name:"raspberry", color:"pink", Similar:(*main.Fruit)(0xc000070390)}
---
json encoding
{"Name":"raspberry","Similar":{"Name":"strawberry","Similar":null}}
---
go-spew
(main.Fruit) {
 Name: (string) (len=9) "raspberry",
 color: (string) (len=4) "pink",
 Similar: (*main.Fruit)(0xc000070390)({
  Name: (string) (len=10) "strawberry",
  color: (string) (len=3) "red",
  Similar: (*main.Fruit)(<nil>)
 })
}

Note the differences:

Depending on your use case, you should choose the method that suits you best.

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

🔟 Convert string to bool in Go

Learn how to parse a string as a bool
introduction strings bool

👯 Remove duplicate spaces from a string in Go

Learn how to remove all redundant whitespaces from a string
introduction strings regex