Cookies management by TermsFeed Cookie Consent
Russia has invaded Ukraine and already killed tens of thousands of civilians, with many more raped or tortured. It's a genocide. We need your help. Let's fight back against the Russian regime.
Help Ukraine! Fight the Russian regime!

πŸ‘£ Print struct variables in Go

introduction strings go-spew

Please consider supporting us by disabling your ad blocker

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.

πŸ’ Concatenate strings in Go

Learn the differences between string concatenation methods
introduction strings

πŸ–¨οΈ 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