外部ライブラリを利用せず、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