LoginSignup
0
0

More than 3 years have passed since last update.

【Golang】クロージャー

Posted at

【Golang】クロージャー

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

package main
//クロージャー
//変数に格納して、実行できる。

import "fmt"


//クロージャーによるジェネレーター
//関数を返す関数、関数を引数に取る関数(渡された関数をそのまま実行する)
//返り値でfunc() intを返す
func incrementGenerator() func() int {
    //変数宣言時のみ
    x := 0
    //ここまでがクロージャーで定義

    //funcを返す 2回目以降はここから
    return func() int {
        x++
        return x
    }
}

//クロージャーの使い方
func circleArea(pi float64) func(radius float64) float64 {
    return func(radius float64) float64 {
        return pi * radius * radius
    }
}

func main() {
    //counterはインナー関数になる
    counter := incrementGenerator()
    fmt.Println(counter())
    //>>1
    fmt.Println(counter())
    //>>2
    fmt.Println(counter())
    //>>3
    fmt.Println(counter())
    //>>4

    //変数に格納して実行
    //引数を先に指定
    //同じ関数で引数を動的にし、インナー関数の引数を動的に買えたい場合
    //pi=3.14
    c1 := circleArea(3.14)
    //c1はインナー関数になる
    //インナー関数の引数
    //radius=2
    fmt.Println(c1(2))
    fmt.Println(c1(3))

    //上記と同様
    c2 := circleArea(3)
    fmt.Println(c2(2))
    fmt.Println(c2(3))
}

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