If it's a "one way" serialization (for debugging or logging or whatever) then fmt.Printf("%#v", var) is very nice. (Update: to put the output into a string instead of printing it, use str := fmt.Sprintf("%#v", var).
If size matters you can use %v, but I like %#v because it will also include the field names and the name of the struct type.
A third variation is %+v which will include the field names, but not the struct type.
They are all documented at the top of the fmt documentation.
If you need two-way serialization JSON, Gob or XML are the easiest/built-in options in Go, see the encoding packages.
Answer from Ask Bjørn Hansen on Stack OverflowIf it's a "one way" serialization (for debugging or logging or whatever) then fmt.Printf("%#v", var) is very nice. (Update: to put the output into a string instead of printing it, use str := fmt.Sprintf("%#v", var).
If size matters you can use %v, but I like %#v because it will also include the field names and the name of the struct type.
A third variation is %+v which will include the field names, but not the struct type.
They are all documented at the top of the fmt documentation.
If you need two-way serialization JSON, Gob or XML are the easiest/built-in options in Go, see the encoding packages.
One popular way of encoding structs into strings is using JSON.
You have certain limitations such as not getting all the information (such as the specific type of each field), only serializing exported fields, and not handling recursive values. But it is a simple standard way of serializing data.
Working example:
package main
import (
"fmt"
"encoding/json"
)
type s struct {
Int int
String string
ByteSlice []byte
}
func main() {
a := &s{42, "Hello World!", []byte{0,1,2,3,4}}
out, err := json.Marshal(a)
if err != nil {
panic (err)
}
fmt.Println(string(out))
}
Give this output:
{"Int":42,"String":"Hello World!","ByteSlice":"AAECAwQ="}
https://play.golang.org/p/sx-xdSxAOG
Why are struct tags strings
How to group strings into a struct / variable?
How convert / print struct as a string
Yes, RTFM about the %v and %#v formats supported by the *f family of functions from the fmt standard package.
For more hardcode stuff, look at go-spew.
More on reddit.comVideos
I recently learned how to use tags in structs. I find it very useful, but parsing them seems to be unnecessarily difficult.
type Log struct {
Time time.Time `db:"ts,s"`
}There's a library called structtag that does it for you, but why couldn't this be a native functionality like so:
type Log struct {
Time time.Time {"db":["ts", "s"]}
}What am missing here?
Is there a shorter/cleaner way to group strings for lookups? I want to have a struct (or something similar) hold all my DB CRUD types in one place. However I find it a little clunky to declare and initialize each field separately.
var CRUDtype = struct {
CreateOne string
ReadOne string
ReadAll string
UpdateOneRecordOneField string
UpdateOneRecordAllFields string
DeleteOne string
}{
CreateOne: "createOne",
ReadOne: "readOne",
ReadAll: "readAll",
UpdateOneRecordOneField: "updateOneRecordOneField",
UpdateOneRecordAllFields: "updateOneRecordAllFields",
DeleteOne: "deleteOne",
}The main reason I'm doing this, is so I can confirm everywhere I use these strings in my API, they'll match. I had a few headaches already where I had typed "craete" instead of "create", and doing this had prevented the issue from reoccurring, but feels extra clunky. At this point I have ~8 of these string grouping variables, and it seems like I'm doing this inefficiently.
Any suggestions / feedback is appreciated, thanks!
Edit - Extra details:
One feature I really like of doing it this way, is when I type in "CRUDtype." it gives me a list of all my available options. And if pick one that doesn't exist, or spell it wrong, I get an immediate clear compiler error.
Is it possible to convert / print a struct as a string
Yes, RTFM about the %v and %#v formats supported by the *f family of functions from the fmt standard package.
For more hardcode stuff, look at go-spew.
As u/kostix said, the "fmt" package and %v. I usually use the %+v variant.
For visualizing more complex structures I prefer kr/pretty over go-spew. I think the output is easier to read, though go-spew's output is more "complete".
Or if appropriate encode to JSON and use that. For large data structures it can make debugging easier because you can inspect the output with for example jq.