Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you ignore the String() method when printing a golang struct?

Tags:

debugging

go

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}
like image 542
Tim Abell Avatar asked Jan 28 '18 21:01

Tim Abell


People also ask

How do I print a string variable in Go?

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.

How do I print a struct with fields in Go?

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.

What are Golang struct tags?

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.


1 Answers

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

like image 151
Tim Abell Avatar answered Sep 19 '22 17:09

Tim Abell