golang如何使用指针打印结构值 [英] golang how to print struct value with pointer

查看:2517
本文介绍了golang如何使用指针打印结构值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

基本上,您必须自己做.有两种方法可以做到这一点.要么只是打印您想要的东西,要么通过添加func String() string为结构实现Stringer接口,当您使用格式%v时会调用该接口.您还可以使用结构形式的格式引用每个值.

Basically, you have to do it yourself. There are two ways to do this. Either just print the thing how you want, or implement the Stringer interface for the struct by adding a func String() string, which gets called when you use the format %v. You could also reference each value in the format which is a struct.

实现Stringer界面是始终获得所需内容的最可靠方法.而且您只需要对每个结构执行一次操作,而不必在打印时对每个格式字符串执行一次.

Implementing the Stringer interface is the surest way to always get what you want. And you only have to do it once per struct, instead of per format string when you print.

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)
}

这篇关于golang如何使用指针打印结构值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆