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

Goの関数を理解する(無名関数・高階関数・クロージャー)

1
Posted at

1. はじめに

この記事でわかること:

  • Goの基本的な関数定義
  • 複数戻り値の受け取り方
  • 無名関数(関数リテラル)
  • 関数を返す関数 / 関数を引数に取る関数
  • クロージャーによる状態保持

2.関数(基本)

関数定義

func Plus(x int, y int) int {
	return x + y
	// func Plus(x, y int) int { ... } // 型が同じならこう書ける
}

呼び出し

i := Plus(3, 5)
fmt.Println(i) // 8

3. 複数戻り値

Goの関数は 複数の値を返せます

func Div(x, y int) (int, int) {
	q := x / y
	r := x % y
	return q, r
}

q, r := Div(10, 3)
fmt.Println(q, r) // 3 1

戻り値を無視する(_)

q, _ := Div(10, 3)
fmt.Println(q) // 3

→Goでは _(ブランク識別子)を使うと、不要な戻り値を捨てられます。

4.名前付き戻り値(named return)

戻り値に名前をつけると、関数内でその変数を使えます。

func Double(price int) (result int) {
	result = price * 2
	return // return result と同じ
}

i := Double(100)
fmt.Println(i) // 200

5.戻り値がない関数

func noreturn() {
	fmt.Println("No Return")
	return
}

noreturn() // No Return

6. 無名関数(関数リテラル)

Goでは関数を 値として扱えるため、無名関数を変数に代入できます。

f := func(x, y int) int {
	return x + y
}
fmt.Println(f(10, 20)) // 30

7. 即時実行関数(IIFE)

無名関数を「その場で定義してすぐ実行」もできます。

i := func(x, y int) int {
	return x + y
}(1, 2)

fmt.Println(i) // 3

8. 関数を返す関数

関数は戻り値として返せます。

func returnFunc() func() {
	return func() {
		fmt.Println("I'm a function")
	}
}
f := returnFunc()
f() // I'm a function

9. 関数を引数に取る関数(高階関数)

関数を引数として受け取り、内部で呼び出すこともできます。

func callFunction(f func()) {
	f()
}
callFunction(func() {
	fmt.Println("I'm a function!!")
}) // I'm a function!!

10. クロージャー(外側の変数を保持する)

クロージャーは、外側の変数を保持し続ける関数です。

func later() func(string) string {
	var store string
	return func(next string) string {
		s := store
		store = next
		return s
	}
}
fc := later()

fmt.Println(fc("Hello")) // (空)
fmt.Println(fc("my"))    // Hello
fmt.Println(fc("name"))  // my
fmt.Println(fc("is"))    // name
fmt.Println(fc("Gopher"))// is

store が「呼び出しのたびに保持されている」のがポイント

参考

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