Customary fmt.Print()
doesn’t print variable names of Go structs, however it doesn’t imply you can’t do this. To print struct variables in Go, you should use the next strategies:
- Use
fmt.Printf()
with format “verbs”%+v
or%#v
. - Convert the struct to JSON and print the output.
- Use exterior packages to pretty-print structs, for instance,
go-spew
.
See the instance beneath and examine these three choices.
package deal foremost
import (
"encoding/json"
"fmt"
"log"
"github.com/davecgh/go-spew/spew"
)
sort Fruit struct {
Title string
colour string
Comparable *Fruit
}
func foremost() {
strawberry := Fruit{
Title: "strawberry",
colour: "crimson",
Comparable: nil,
}
raspberry := Fruit{
Title: "raspberry",
colour: "pink",
Comparable: &strawberry,
}
// fmt.Printf with format verbs
fmt.Printf("fmt.Printf with format verbsn")
fmt.Printf("%+vn%#vn", raspberry, raspberry)
// json encoding
fmt.Printf("---njson encodingn")
jsonData, err := json.Marshal(&raspberry)
if err != nil {
log.Deadly(err)
}
fmt.Println(string(jsonData))
// go-spew
fmt.Printf("---ngo-spewn")
spew.Dump(raspberry)
}
Output:
fmt.Printf with format verbs
{Title:raspberry colour:pink Comparable:0xc000070390}
foremost.Fruit{Title:"raspberry", colour:"pink", Comparable:(*foremost.Fruit)(0xc000070390)}
---
json encoding
{"Title":"raspberry","Comparable":{"Title":"strawberry","Comparable":null}}
---
go-spew
(foremost.Fruit) {
Title: (string) (len=9) "raspberry",
colour: (string) (len=4) "pink",
Comparable: (*foremost.Fruit)(0xc000070390)({
Title: (string) (len=10) "strawberry",
colour: (string) (len=3) "crimson",
Comparable: (*foremost.Fruit)(<nil>)
})
}
Be aware the variations:
fmt.Printf()
prints solely area values, which within the case of a pointer, it’s the reminiscence handle of the variable it factors to.- Encoding to JSON requires all struct fields to be exported (the primary letter capitalized). In any other case, unexported fields corresponding to
colour
is not going to seem within the ensuing JSON. - Package deal
go-spew
prints detailed details about the struct, however it’s an exterior dependency that must be imported.
Relying in your use case, you need to select the tactic that fits you finest.