LoginSignup
1
1

More than 3 years have passed since last update.

【Golang】Go言語基礎 構造体について②(埋め込み)

Posted at

今回は【Golang】Go言語の基礎 構造体について①の続編です。

Goにはクラスという概念がありません。したがって継承という概念もないです。しかし、その代わりに構造体の埋め込み(Embedded)というものがあります。

早速書いてみる


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
}

//構造体VertexをVertex3Dに埋め込む
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 int) *Vertex{
    return &Vertex{x, y}
}

func main() {
    v := New(3, 4)
    v.Scale(10)
    fmt.Println(v.Area()) //=> 1200



}

↑のように構造体を埋め込むことができます。Vertex3Dの構造体では新しくzを追加しています。
埋め込んだ構造体(Vertex3D)では Vertexで定義したx, yを使うことができます。継承とほぼ同じですね。

ちなみにfunc New の部分はコンストラクタです。rubyでいうinitializeのような処理をしていると思ってもらえると
理解しやすいと思います!

(ここまでは上と同じなので省略

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

func main() {
    //新しく5を追加する。
    v := New(3, 4, 5)
    v.Scale3D(10)
    fmt.Println(v.Area())
    fmt.Println(v.Area3D()) => 60000
}

試しに新しく定義したzに5を代入してみると60000が返ってきました!

いつも最後まで読んでいただきありがとうございます

ご指摘やご質問などあればコメントいただけると嬉しいです!

1
1
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
1
1