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

I have a golang structure and I created a String() method for the program to work properly. Now I want to see the entire contents of the structure. 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 data of the original structure?

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 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} 
+6
source share
3 answers

Use the format %#v

 fmt.Printf("%#v", bar) 

Outputs:

 main.Foo{Jekyl:"good", Hyde:"evil"} 

ref fooobar.com/questions/818182 / ...

https://play.golang.org/p/YWIf6zGU-En

+10
source

While your answer is correct, it is common practice to use a different type to remove all structure methods and use others (this is usually used when sorting / disassembling).

If the type is defined as type stripped Foo , then the Foo.String() method Foo.String() no longer be used.

Code: https://play.golang.org/p/Ba2VvLAm92a

Exit: {Jekyl:good Hyde:evil}

+1
source

Another way to print a complete pair of key values ​​for any object:

 package main import ( "encoding/json" "fmt" ) type Foo struct { Jekyl string Hyde string } func main() { bar := Foo{Jekyl: "good", Hyde: "evil"} b, err := json.Marshal(bar) if err != nil { fmt.Println("error marshaling object") return } fmt.Println("bar data : ", string(b)) } 

Output:

  bar data : {"Jekyl":"good","Hyde":"evil"} 

Go to the playground https://play.golang.org/p/VJZNmpC_wNJ

0
source

Source: https://habr.com/ru/post/1275005/


All Articles