首页 >后端开发 >Golang >如何在 Go 中打印嵌套结构的值而不是指针?

如何在 Go 中打印嵌套结构的值而不是指针?

Patricia Arquette
Patricia Arquette原创
2024-11-29 16:44:10345浏览

How to Print the Value, Not the Pointer, of Nested Structs in Go?

在 Go 中打印带有指针的结构体值

在 Go 中,当打印包含指针的结构体值时,通常会打印指针地址的实际值。当尝试检查嵌套结构的内容时,这可能会出现问题。

如何打印 B 结构体值而不是指针

要解决此问题,您可以有两个选项:

  1. 实现 Stringer接口:

    为 A 和 B 结构体实现 String() 方法。此方法返回结构的格式化字符串表示形式。在实现中,打印所需的值而不是指针。

    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}}
        fmt.Println(a)
    }
  2. 手动打印值:

    访问实际值B 手动构造并直接打印。

    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("A{a:%d, B:{b:%d}}\n", a.a, a.B.b)
    }

以上是如何在 Go 中打印嵌套结构的值而不是指针?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn