登录
首页 >  Golang >  Go问答

Go:以优雅的方式使用指针值打印嵌套对象

来源:stackoverflow

时间:2024-02-07 16:00:24 136浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《Go:以优雅的方式使用指针值打印嵌套对象》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

如何漂亮地打印下面的对象?

package main

// object: {
//   table: {
//     files: [],
//     data: {
//        code: {
//          name: "name",
//          count: 123,
//       }
//     }
//
// }

import (
    "encoding/json"
    "fmt"
    "log"
)

type container map[string]*table

type table struct {
    files []string
    data  map[string]*data
}

type data struct {
    name  string
    count int
}

func main() {

    object := container{
        "table1": {
            files: []string{"file-1.1"},
            data: map[string]*data{
                "xyz": {
                    name:  "foo",
                    count: 123,
                },
            },
        },
        "table2": {
            files: []string{
                "file-2.1",
                "file-2.2",
                "file-2.3",
            },
        },
        "table3": {files: []string{"file-3.1"}},
    }

    fmt.printf("%#v\n", &object)
    objectjson, err := json.marshalindent(object, "", "  ")
    if err != nil {
        log.fatalf(err.error())
    }
    fmt.printf("%s\n", objectjson)

}

https://go.dev/play/p/frwzsfwgynu

使用此代码,我仅获得对象的第一个深度:

&main.Container{"table1":(*main.Table)(0xc00005c020), "table2":(*main.Table)(0xc00005c040), "table3":(*main.Table)(0xc00005c060)}
{
  "table1": {},
  "table2": {},
  "table3": {}
}

Program exited.

正确答案


这与“深度”无关。一般情况下,您无法使用 fmt.printfjson.marshal 漂亮地打印私有、未导出的字段。如果您希望该变量在编组时出现,请导出它们(即,将 table.files 更改为 table.files。go 会将导出的字段编组到任意深度:

{
  "foo1": {
    "Files": [
      "file-1.1"
    ],
    "Data": {
      "XYZ": {
        "Name": "foo",
        "Count": 123
      }
    }
  },
  "foo2": {
    "Files": [
      "file-2.1",
      "file-2.2",
      "file-2.3"
    ],
    "Data": null
  },
  "foo3": {
    "Files": [
      "file-3.1"
    ],
    "Data": null
  }
}

如果您想使用 fmt.printf("%v", ...) 漂亮地打印对象,那么您需要在每个类上实现 stringer 接口。此时,如何打印对象的决定完全取决于您,并且您可以以您想要的任何格式包含公共或私有成员。

理论要掌握,实操不能落!以上关于《Go:以优雅的方式使用指针值打印嵌套对象》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>