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 5 years have passed since last update.

ポインタ

Posted at

教科書などにあるポインタ

package main

import "fmt"

func main() {
	var n int = 100
	var p *int = &n

	fmt.Println(n)  // 100
	fmt.Println(&n) // 0xc000014078
	// fmt.Println(*n) // ポイント型ではないのでエラーになる
	fmt.Println(p)  // 0xc000014078
	fmt.Println(*p) // 100
	fmt.Println(&p) // 0xc00000c028
}

イメージは以下の通り
スクリーンショット 2018-12-29 1.36.44.png

構造体のポインタ

そして、分からないのが構造体のポインタ

package main

import "fmt"

type Vertex struct {
	X int
	Y int
}

func main() {
	v := Vertex{1, 2}
	p := &v
	fmt.Println(v)  // {1 2}
	fmt.Println(&v) // &{1 2}

	fmt.Println(p)  // &{1 2}
	fmt.Println(*p) // {1 2}
	fmt.Println(&p) // 0xc00000c028
}

イメージは以下の通り
スクリーンショット 2018-12-29 1.48.53.png

アドレスが、&{1 2} という形式になっている???
わかる方教えてください。

直接アドレスと指定した場合は以下の通り

package main

import "fmt"

type Vertex struct {
	X int
	Y int
}

func main() {
	v := &Vertex{1, 2}
	fmt.Println(v)  // &{1 2}
	fmt.Println(*v) // {1 2}
	fmt.Println(&v) // 0xc00000c028
}

image.png

関数経由で、構造体を宣言する場合(カプセル化に利用できる?)
イメージは上と同じ

package main

import "fmt"

type Vertex struct {
	x, y int
}

func New(x, y int) *Vertex {
	return &Vertex{x, y}
}

func main() {
	v := New(1, 2)  // v := &Vertex{1, 2} と同じ
	fmt.Println(v)  // &{1 2}
	fmt.Println(*v) // {1 2}
	fmt.Println(&v) // 0xc00000c028
}
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?