I have a golang struct, and have created a String()
method for use in the program's normal operation. I now want to see the whole contents of the struct. I tried the usual %+v
format but it seems to use the String()
method instead of showing me all the fields. How can I output the raw structure data?
Example: https://play.golang.org/p/SxTVOtwVV-9
package main
import (
"fmt"
)
type Foo struct {
Jekyl string
Hyde string
}
func (foo Foo) String() string {
return foo.Jekyl // how I want it to show in the rest of the program
}
func main() {
bar := Foo{Jekyl: "good", Hyde: "evil"}
fmt.Printf("%+v", bar) // debugging to see what's going on, can't see the evil side
}
Outputs
good
But I want to see what you get without the String() method implemented
{Jekyl:good Hyde:evil}
To print a string in Golang we have to use the package fmt which contains the input/output functions. The correct specifier tells the data type of variable we are printing. The specifiers we can use to print the strings are: %s − By using this we can print the uninterpreted strings or slice.
In Golang, we can print the structure's fields with their names using the following: Marshal() function of encoding/json package. Printf() function of fmt package.
A struct tag is additional meta data information inserted into struct fields. The meta data can be acquired through reflection. Struct tags usually provide instructions on how a struct field is encoded to or decoded from a format.
Use the %#v
format
fmt.Printf("%#v", bar)
Outputs:
main.Foo{Jekyl:"good", Hyde:"evil"}
ref https://stackoverflow.com/a/26116578/10245
https://play.golang.org/p/YWIf6zGU-En
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With