Go 入門

Go言語入門⑪ ~メソッド・コンストラクタ・Embedded~

[box class="blue_box" title="☑本記事の内容"]

  • メソッド
  • コンストラクタ
  • Embedded

[/box]
参考資料:現役シリコンバレーエンジニアが教えるGo入門 + 応用でビットコインのシストレFintechアプリの開発
[box class="glay_box" title="Contents"]

  1. Go言語入門 -メソッド-
  2. Go言語入門 -コンストラクタ-
  3. Go言語入門 -Embedded-

[/box]

Go言語入門 -メソッド-

[box class="yellow_box" title="✔Go言語入門 -メソッド-の目次"]

[/box]

メソッド

[box class="glay_box"]

  • ドット(.)をつけることで呼び出されるものをやる
  • オブジェクトの考え方と似ている
  • structとの結び付きがわかりやすいため、他の人が見るときに良い

[/box]

package main

import "fmt"

type Vertex struct {
	X, Y int
}

func (v Vertex) Area() int {
	return v.X * v.Y
}

func Area(v Vertex) int {
	return v.X * v.Y
}

func main() {
	v := Vertex{3, 4}
    fmt.Println(Area(v))

	fmt.Println(v.Area())
}
(結果)
12
12

ポインタレシーバーと値レシーバー

[box class="glay_box"]

  • 値を書き換えたい場合はポインタを使用する
  • ポインタを渡している関数をポインタレシーバー
  • 値を渡している関数は値レシーバー

[/box]

package main

import "fmt"

type Vertex struct {
	X, Y int
}

func (v *Vertex) Scale(i int) {
	v.X = v.X * i
	v.Y = v.Y * i
}

func (v Vertex) Area() int {
	return v.X * v.Y
}

func main() {
	v := Vertex{3, 4}
	v.Scale(10)
	fmt.Println(v.Area())
}
(結果)
1200
package main

import "fmt"

type Vertex struct {
	X, Y int
}

func (v Vertex) Scale(i int) {
	v.X = v.X * i
	v.Y = v.Y * i
}

func (v Vertex) Area() int {
	return v.X * v.Y
}

func main() {
	v := Vertex{3, 4}
	v.Scale(10)
	fmt.Println(v.Area())
}
(結果)
12

Go言語入門 -コンストラクタ-

[box class="yellow_box" title="✔Go言語入門 -コンストラクタ-の目次"]

[/box]

基本的なこと

[box class="glay_box"]

  • 別のプログラミング言語ではclassを使うが、Goにはclassは存在しない
  • Vertexは小文字にすると他のパッケージでは呼び出しが出来ない
  • Goの場合はNewを使用して他のパッケージから値を呼び出す

[/box]

package main

import "fmt"

type Vertex struct {
	x, y int
}

func (v Vertex) Area() int {
	return v.x * v.y
}

func (v *Vertex) Scale(i int) {
	v.x = v.x * i
	v.y = v.y * i
}

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

func main() {
	v := New(3, 4)
	v.Scale(10)
	fmt.Println(v.Area())
}
(結果)
1200

Go言語入門 -Embedded-

[box class="yellow_box" title="✔Go言語入門 -Embedded-の目次"]

[/box]

基本的なこと

[box class="glay_box"]

  • 他のプログラミング言語での継承に似た動作のもの
  • 前の関数の値を継承して、値を出力する
  • すぐに理解は難しいので色々いじってみて理解を深めるのがいい

[/box]

package main

import "fmt"

type Vertex struct {
	x, y int
}

func (v Vertex) Area() int {
	return v.x * v.y
}

func (v *Vertex) Scale(i int) {
	v.x = v.x * i
	v.y = v.y * i
}

type Vertex3D struct {
	Vertex
	z int
}

func (v Vertex3D) Area3D() int {
	return v.x * v.y * v.z
}

func (v *Vertex3D) Scale3D(i int) {
	v.x = v.x * i
	v.y = v.y * i
	v.z = v.z * i
}

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

func main() {
	v := New(3, 4, 5)
	v.Scale3D(10)
	fmt.Println(v.Area3D())
}
(結果)
60000

Go言語入門⑫へ ≫

≪ Go言語入門⑩へ

目次

-Go, 入門