☑本記事の内容
- メソッド
- コンストラクタ
- Embedded
Go言語入門 -メソッド-
✔Go言語入門 -メソッド-の目次
メソッド
- ドット(.)をつけることで呼び出されるものをやる
- オブジェクトの考え方と似ている
- structとの結び付きがわかりやすいため、他の人が見るときに良い
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
ポインタレシーバーと値レシーバー
- 値を書き換えたい場合はポインタを使用する
- ポインタを渡している関数をポインタレシーバー
- 値を渡している関数は値レシーバー
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言語入門 -コンストラクタ-
✔Go言語入門 -コンストラクタ-の目次
基本的なこと
- 別のプログラミング言語ではclassを使うが、Goにはclassは存在しない
- Vertexは小文字にすると他のパッケージでは呼び出しが出来ない
- Goの場合はNewを使用して他のパッケージから値を呼び出す
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-
✔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
}
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