11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Goで構造体をダンプする

Last updated at Posted at 2015-01-09
package main

import "fmt"

import "github.com/kr/pretty"

type Node struct {
    TagName   string
    Id        string
    ClassName string
    Children  []*Node
}

func (n *Node) appendChild(child *Node) {
    n.Children = append(n.Children, child)
}

func main() {
    body := &Node{TagName: "body", Id: "main"}
    {
        header := &Node{TagName: "div", Id: "header"}
        content := &Node{TagName: "div", Id: "content"}
        footer := &Node{TagName: "div", Id: "footer"}

        body.appendChild(header)
        body.appendChild(content)
        body.appendChild(footer)

        title := &Node{TagName: "h1", Id: "title", ClassName: "title"}
        content.appendChild(title)

    }
    fmt.Printf("%v\n", pretty.Formatter(body))

    fmt.Printf("%+v\n", pretty.Formatter(body))
    fmt.Printf("%+ v\n", pretty.Formatter(body))

    fmt.Printf("%#v\n", pretty.Formatter(body))
    fmt.Printf("%# v\n", pretty.Formatter(body))

}

実行結果

&{body main  [0xc208018280 0xc2080182d0 0xc208018320]}
&{TagName:body Id:main ClassName: Children:[0xc208018280 0xc2080182d0 0xc208018320]}
&{TagName:body Id:main ClassName: Children:[ 0xc208018280  0xc2080182d0  0xc208018320]}
&main.Node{TagName:"body", Id:"main", ClassName:"", Children:[]*main.Node{(*main.Node)(0xc208018280), (*main.Node)(0xc2080182d0), (*main.Node)(0xc208018320)}}
&main.Node{
    TagName:   "body",
    Id:        "main",
    ClassName: "",
    Children:  {
        &main.Node{
            TagName:   "div",
            Id:        "header",
            ClassName: "",
            Children:  nil,
        },
        &main.Node{
            TagName:   "div",
            Id:        "content",
            ClassName: "",
            Children:  {
                &main.Node{
                    TagName:   "h1",
                    Id:        "title",
                    ClassName: "title",
                    Children:  nil,
                },
            },
        },
        &main.Node{
            TagName:   "div",
            Id:        "footer",
            ClassName: "",
            Children:  nil,
        },
    },
}

結論

fmt.Printf("%# v", pretty.Formatter(obj))

↑これが良さそう。

11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?