3
0

More than 3 years have passed since last update.

Go methodについて

Last updated at Posted at 2019-12-06

Goにはクラスの仕組みが無い代わりに、型にメソッドを定義できるとのこと。
今までやってきた言語にはなかった仕組みなので理解したい

そもそも、functionとmethodは別ものらしい...え?

まず、一般的な関数について
このように、func <関数名> (引数) (返り値)の順番で記述する

main.go
func adder(x, y int) (z int) {
  z = x + y
  return z
}

Goは<関数名>の前にもう一つ()をつけることができる

main.go
type Vertex struct { // 構造体
  x, y float64
}
func (v Vertex) abc() float64 {
...
}
func (レシーバ ) 関数名引数戻り値の型 {
    // 処理
    return

struct(構造体)と関数を結びつけること、これがGoのオブジェクト指向らしい。
Goにはクラスがないのでstructに関数を結びつけることによって関係性とプログラム全体の構成がわかりやすくなる。

参考

昔の自分に送るGolangの基礎的なこと(型確認・Slice・method)

3
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
3
0