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アプリケーション作成までの学習を終えたので、復習を兼ねてまとめていく。 基礎〜応用まで。

package main 
//メソッドとポインタレシーバーと値レシーバー
//メソッド class内関数のselfを使えるようなイメージ(Goにはクラスが無い)
//コードがわかりやすい


import (
	"fmt"
)


//バーテックスを作成
type Vertex struct {
	X, Y int
}


//1
func Scale1(v *Vertex, i int) {
	v.X = v.X * i
	v.Y = v.Y * i	
}

//2
//メソッド
func (v Vertex) Area() int {
	return v.X * v.Y
}

//メソッド
//structのポインタを渡す 値を上書きする
//原則ポインタ型にする
//引数も渡す
func (v *Vertex) Scale2(i int) {
	v.X = v.X * i
	v.Y = v.Y * i
}

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

	//1
	//関数の場合
	Scale1(&v, 2)
	fmt.Println(v)
	//>>{6 8}

	//2 
	//メソッドの場合 pythonのselfのイメージ
	v.Scale2(2)
	fmt.Println(v)
	//>>{12 16}

	//scaleで書き換わった後なので
	fmt.Println(v.Area())
	//>192
}
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?