0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

外部ライブラリを利用せず、structをPretty Printしたい

Posted at

外部ライブラリを利用せず、Go言語でstructをPretty Printする方法を2つ紹介します。

fmtパッケージを利用する

fmt.Printfを利用する場合、書式指定子に%+vを指定すればよいです。

package main

import (
	"fmt"
	"time"
)

type Employee struct {
	ID       int
	Name     string
	HireDate time.Time
}

type Department struct {
	ID        int
	Name      string
	Employees []Employee
}

func main() {
	department := Department{
		ID:   9876,
		Name: "営業部",
		Employees: []Employee{
			Employee{ID: 100, Name: "佐藤", HireDate: time.Date(2001, 1, 1, 1, 1, 1, 1, time.UTC)},
			Employee{ID: 200, Name: "田中", HireDate: time.Date(2002, 2, 2, 2, 2, 2, 2, time.UTC)},
			Employee{ID: 300, Name: "高橋", HireDate: time.Date(2003, 3, 3, 3, 3, 3, 3, time.UTC)},
		},
	}

	fmt.Printf("%+v\n", department)
}

実行結果は以下の通りです。

$ go run main.go
{ID:9876 Name:営業部 Employees:[{ID:100 Name:佐藤 HireDate:2001-01-01 01:01:01.000000001 +0000 UTC} {ID:200 Name:田中 HireDate:2002-02-02 02:02:02.000000002 +0000 UTC} {ID:300 Name:高橋 HireDate:2003-03-03 03:03:03.000000003 +0000 UTC}]}

jsonパッケージを利用する

structをjsonとして扱う方法もあります。

package main

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

type Employee struct {
	ID       int
	Name     string
	HireDate time.Time
}

type Department struct {
	ID        int
	Name      string
	Employees []Employee
}

func main() {
	department := Department{
		ID:   9876,
		Name: "営業部",
		Employees: []Employee{
			Employee{ID: 100, Name: "佐藤", HireDate: time.Date(2001, 1, 1, 1, 1, 1, 1, time.UTC)},
			Employee{ID: 200, Name: "田中", HireDate: time.Date(2002, 2, 2, 2, 2, 2, 2, time.UTC)},
			Employee{ID: 300, Name: "高橋", HireDate: time.Date(2003, 3, 3, 3, 3, 3, 3, time.UTC)},
		},
	}

	b, err := json.MarshalIndent(department, "", "  ")
	if err != nil {
		log.Fatalf("unexpected error: %w", err)
	}
	fmt.Println(string(b))
}

実行結果は以下の通りです。

$ go run main.go
{
  "ID": 9876,
  "Name": "営業部",
  "Employees": [
    {
      "ID": 100,
      "Name": "佐藤",
      "HireDate": "2001-01-01T01:01:01.000000001Z"
    },
    {
      "ID": 200,
      "Name": "田中",
      "HireDate": "2002-02-02T02:02:02.000000002Z"
    },
    {
      "ID": 300,
      "Name": "高橋",
      "HireDate": "2003-03-03T03:03:03.000000003Z"
    }
  ]
}

環境情報

$ go version
go version go1.22.1 linux/amd64
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?