use*_*949 5 printing struct pointers go
package main
import "fmt"
type A struct {
a int32
B *B
}
type B struct {
b int32
}
func main() {
a := &A{
a: 1,
B: &B{
b: 2,
},
}
fmt.Printf("v ==== %+v \n", a)
}
//ret: v ==== &{a:1 B:0xc42000e204}
//??? how to print B's content but not pointer
Run Code Online (Sandbox Code Playgroud)
Ray*_*ear 11
基本上,你必须自己做。有两种方法可以做到这一点。要么只是打印你想要的东西,要么Stringer
通过添加 a 来实现结构的接口,func String() string
当你使用 format 时会调用它%v
。您还可以以结构格式引用每个值。
实现Stringer
接口是始终获得所需内容的最可靠方法。而且您只需在每个结构中执行一次,而不是在打印时按格式字符串执行。
https://play.golang.org/p/PKLcPFCqOe
package main
import "fmt"
type A struct {
a int32
B *B
}
type B struct{ b int32 }
func (aa *A) String() string {
return fmt.Sprintf("A{a:%d, B:%v}",aa.a,aa.B)
}
func (bb *B) String() string {
return fmt.Sprintf("B{b:%d}",bb.b)
}
func main() {
a := &A{a: 1, B: &B{b: 2}}
// using the Stringer interface
fmt.Printf("v ==== %v \n", a)
// or just print it yourself however you want.
fmt.Printf("v ==== A{a:%d, B:B{b:%d}}\n", a.a, a.B.b)
// or just reference the values in the struct that are structs themselves
// but this can get really deep
fmt.Printf("v ==== A{a:%d, B:%v}", a.a, a.B)
}
Run Code Online (Sandbox Code Playgroud)
dga*_*002 10
另一个简单的解决方案是使用封送处理来打印结构。这仅适用于通过将结构内的第一个字符大写来导出(公共)变量。
package main
import (
"fmt"
"gopkg.in/yaml.v2"
"encoding/json"
)
type A struct {
Aa int32
B *B
}
type B struct {
Bb int32
}
func main() {
a := &A{
Aa: 1,
B: &B{
Bb: 2,
},
}
aJSON, _ := json.Marshal(a)
fmt.Printf("JSON Print - \n%s\n", string(aJSON))
aYAML, _ := yaml.Marshal(a)
fmt.Printf("YAML Print - \n%s\n", string(aYAML))
}
Run Code Online (Sandbox Code Playgroud)
输出 :-
JSON Print -
{"Aa":1,"B":{"Bb":2}}
YAML Print -
aa: 1
b:
bb: 2
Run Code Online (Sandbox Code Playgroud)
如果多次打印结构,则实现 Stringer 接口,如下所示:-
package main
import (
"fmt"
"gopkg.in/yaml.v2"
)
type A struct {
Aa int32
B *B
}
func (a A) String() string {
bytes, _ := yaml.Marshal(a)
return string(bytes)
}
type B struct {
Bb int32
}
func main() {
a := &A{
Aa: 1,
B: &B{
Bb: 2,
},
}
fmt.Printf("YAML Print - \n%+v\n", a)
}
Run Code Online (Sandbox Code Playgroud)
输出 -
YAML Print -
aa: 1
b:
bb: 2
Run Code Online (Sandbox Code Playgroud)
小智 6
当您进入更大的结构时,编写一堆自定义 String 函数会变得很痛苦。Goconvey 目前使用以下项目来显示任何大小结构的差异和预期/实际输出:https : //github.com/luci/go-render/blob/master/render/render.go#L51。它包括显示指针值。
如果您需要将输出作为代码重用(例如fmt.Printf("%#v", a)
但包含指针值),我有上述项目的分叉版本,它将完整嵌套的指针呈现为可重用代码:
package main
import (
"fmt"
"github.com/gdexlab/go-render/render"
)
type A struct {
a int32
B *B
}
type B struct {
b int32
}
func main() {
a := &A{
a: 1,
B: &B{
b: 2,
},
}
output := render.AsCode(a)
fmt.Println(output)
}
// outputs: "&A{a:1, B:&B{b:2}}" compared to initial version of "&{a:1 B:0xc42000e204}"
Run Code Online (Sandbox Code Playgroud)
Go Playground 示例:https : //play.golang.org/p/tcfJYb0NnVf
归档时间: |
|
查看次数: |
8473 次 |
最近记录: |