128
107

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言語でPHPのvar_dumpやJavaScriptのconsole.log的なもの

Last updated at Posted at 2013-12-11

デバッグするとき値の中身を見たいもの。Go言語にもPHPの var_dump やJavaScriptの console.log のように、値の中身をプリントすることができる関数がある。

関数 意味
fmt.Printf("%v", value) デフォルトフォーマットを適用した値 &{bar baz}
fmt.Printf("%+v", value) デフォルトフォーマットを適用した値で、構造体のときフィールド名が出る &{Bar:bar Baz:baz}
fmt.Printf("%#v", value) Go言語の構文で表現した値 &main.Foo{Bar:"bar", Baz:"baz"}
fmt.Printf("%T", value) Go言語の構文で表現した型 *main.Foo

ちなみに、fmt ではなく log パッケージの Printf もある。違いは以下:

関数 パッケージ 日付が 最後が
fmt.Printf import "fmt" 出ない 改行されない
log.Printf import "log" 出る 改行される

使い方の例

main.go
package main

import (
	"log"
)

type Foo struct {
	Bar string
	Baz string
}

func main() {
	foo := &Foo{"bar", "baz"}
	log.Printf("%v", foo)
	log.Printf("%+v", foo)
	log.Printf("%#v", foo)
	log.Printf("%T", foo)
}

出力結果

2013/12/11 21:52:10 &{bar baz}
2013/12/11 21:52:10 &{Bar:bar Baz:baz}
2013/12/11 21:52:10 &main.Foo{Bar:"bar", Baz:"baz"}
2013/12/11 21:52:10 *main.Foo

var_dump っぽく実装してみた

package main

import (
	"fmt"
)

type Foo struct {
    Bar string
    Baz string
}

func main() {
    foo := &Foo{"bar", "baz"}
	var_dump(1, true, nil, "string", foo)
}

func var_dump(v ...interface{}) {
	for _, vv := range(v) {
		fmt.Printf("%#v\n", vv)
	}
}

出力結果

1
true
<nil>
"string"
&main.Foo{Bar:"bar", Baz:"baz"}

UPDATE 2013/12/12 spew

github.com/davecgh/go-spew/spewを使うと改行もしてくれて見やすい

main.go
package main

import (
	"github.com/davecgh/go-spew/spew"
)

type Name struct {
	FirstName string
	LastName string
}

type Address struct {
	Country string
	PostalCode string
	Address string
}

type Person struct {
	Name Name
	Address Address
}

func main() {
	person := &Person{
		Name{"Cynthia", "Stone"},
		Address{"us", "02110", "1091 Lyon Avenue, Boston"},
	}
	spew.Dump(person) // ここ!
}

出力結果

(*main.Person)(0x2102bd230)({
 Name: (main.Name) {
  FirstName: (string) "Cynthia",
  LastName: (string) "Stone"
 },
 Address: (main.Address) {
  Country: (string) "us",
  PostalCode: (string) "02110",
  Address: (string) "1091 Lyon Avenue, Boston"
 }
})
128
107
3

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
128
107

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?