Go:如何漂亮地打印带有指针值的嵌套对象?

Go: How to pretty print nested objects with pointers values?

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

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 通常 pretty-print 私有,un-exported 字段。如果您希望变量在编组时出现,请导出它们(即,将 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", ...) 漂亮地打印对象,那么您需要在每个 class 上实现 Stringer 接口。到那时,关于如何打印对象的决定 完全 取决于你,你可以包含 public 或你喜欢的任何格式的私有成员。