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?

More than 3 years have passed since last update.

【Go言語/golang】値とポインタってどう分ける?ゼロ値のまとめ

Last updated at Posted at 2021-03-11

変数を宣言した時に、varで定義するのか:=で定義するのか、newで作成すればいいのか迷うことがありました。
そこで、備忘録も兼ねて、どのように定義をした時に、出力がどうなるかを簡単にまとめました。

値の定義


package main

import "fmt"

func main() {
	var a int
	var b string
	var c []string
	var d map[int]string
	var e = make([]string, 1)
	var f = make(map[int]string)
	var g interface{}
	h := map[int]string{}

	testprint("a", a)
	testprint("b", b)
	testprint("c", c)
	testprint("d", d)
	testprint("e", e)
	testprint("f", f)
	testprint("g", g)
	testprint("h", h)
}

func testprint(s string, i interface{}) {
	fmt.Printf("%s: %#v\n",s, i)
}
// 出力結果
a: 0
b: ""
c: []string(nil)
d: map[int]string(nil)
e: []string{""}
f: map[int]string{}
g: <nil>
h: map[int]string{}

ポインタで定義

package main

import "fmt"

func main() {
	var a *int
	var b *string
	var c *[]string
	var d *map[int]string
	var g *interface{}

	testprint("a", a)
	testprint("b", b)
	testprint("c", c)
	testprint("d", d)
	testprint("g", g)
}

func testprint(s string, i interface{}) {
	fmt.Printf("%s: %v\n", s, i)
}
// 出力結果
a: <nil>
b: <nil>
c: <nil>
d: <nil>
g: <nil>

それぞれにnilを入れてみる

package main

import "fmt"

func main() {
	var a int
	var b string
	var c []string
	var d map[int]string
	var e = make([]string, 1)
	var f = make(map[int]string)
	var g interface{}
	h := map[int]string{}
 	type hoge struct{}
	var i hoge
	var j [3]int


	// a = nil // error: cannot use nil as type int in assignment
	// b = nil // error: cannot use nil as type string in assignment
	c = nil
	d = nil
	f = nil
	g = nil
	h = nil
	// i = nil // error: cannot use nil as type hoge in assignment
	// j = nil // error: cannot use nil as type [3]int in assignment


	testprint("a", a)
	testprint("b", b)
	testprint("c", c)
	testprint("d", d)
	testprint("e", e)
	testprint("f", f)
	testprint("g", g)
	testprint("h", h)
}

func testprint(s string, i interface{}) {
	fmt.Printf("%s: %#v\n",s, i)
}
// 出力結果
a: 0
b: ""
c: []string(nil)
d: map[int]string(nil)
e: []string{""}
f: map[int]string(nil)
g: <nil>
h: map[int]string(nil)

int, string以外はnilが入りました。
プリミティブについては、nilが入らないので、覚えておきましょう。

0
0
1

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?