Function that provides ability to print variable values in golang. No external dependencies are used. Try it online: https://go.dev/play/p/mxbwyIUSLVZ
Sometimes printing some variable value in golang might be challenging or not easy to follow. Current implementation just simply wraps passed object into json and prints it in STDOUT.
As a bonus it can print label for provided variable value to make it easier to distinguish in logs. + Line on which it was called is listed above variable value output.
type room struct {
Number int
Color string
IsFree bool
}
func main() {
time, _ := time.Parse("2006-01-02", "2020-05-22")
room := &room{
Number: 7,
Color: "purple",
IsFree: true,
}
prettyPrint("room", room)
prettyPrint(room.IsFree)
prettyPrint("room number", room.Number)
prettyPrint(time)
}
Provides following output:
[PrettyPrint] 11-10-2009 23:00:00 -- /tmp/sandbox1984072684/prog.go:51
[PrettyPrint] 11-10-2009 23:00:00 -- room: {
"Number": 7,
"Color": "purple",
"IsFree": true
}
[PrettyPrint] 11-10-2009 23:00:00 -- /tmp/sandbox1984072684/prog.go:52
[PrettyPrint] 11-10-2009 23:00:00 -- [
true
]
[PrettyPrint] 11-10-2009 23:00:00 -- /tmp/sandbox1984072684/prog.go:53
[PrettyPrint] 11-10-2009 23:00:00 -- room number: 7
[PrettyPrint] 11-10-2009 23:00:00 -- /tmp/sandbox1984072684/prog.go:54
[PrettyPrint] 11-10-2009 23:00:00 -- [
"2020-05-22T00:00:00Z"
]
Thanks for your gist! I like the function used it and extended it to dump the json string into file instead of stdout: https://gist.github.com/amaddio/15f44de58712251870bcdd13e4423125
If I can cut out some time I'll rewrite the function to parametrize the write object. So one could simply choose between, stdout, file or any other object that implements
io.Writer interface