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.

【Golang】構造体③埋め込み

Posted at

#【Golang】構造体③埋め込み

Golangの基礎学習〜Webアプリケーション作成までの学習を終えたので、復習を兼ねてまとめていく。 基礎〜応用まで。

//Embedded
//クラスの継承のイメージ
//埋め込み



//Pythonの場合
/*
class Vertex(object):

    def __init__(self, x, y):
        self._x = x
        self._y = y

    def area(self):
        return self._x * self._y

    def scale(self, i):
        self._x = self._x * i
        self._y = self._y * i


class Vertex3D(Vertex):

    def __init__(self, x, y, z):
        super().__init__(x, y)
        self._z = z

    def area_3d(self):
        return self._x * self._y * self._z

    def scale_3d(self, i):
        self._x = self._x * i
        self._y = self._y * i
        self._z = self._z * i


v = Vertex3D(3, 4, 5)
v.scale(10)
print(v.area())
print(v.area_3d())
*/


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
}

//3D
type Vertex3D struct {
	//埋め込み
	//上記で作成した、Vertexを渡すと中身をそのまま渡せる
	Vertex
	z int
}


func NewV3D(x, y, z int) *Vertex3D {
	//埋め込みなので、このように書く。
	//return &Vertex3D{3, 4, 5}ではできない
	return &Vertex3D{Vertex{x, y}, z}
}

func main() {
    v3d := NewV3D(3, 4, 5)

    //どちらでもアクセスできる
    fmt.Println(v3d.x)
    fmt.Println(v3d.Vertex.x)

	
	fmt.Println(v3d)

	v3d.Scale(5)

	fmt.Println(v3d)
}
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?