Skip to content

Instantly share code, notes, and snippets.

@sugilog
Created January 4, 2015 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sugilog/aea0c2a082e13b2b1e4d to your computer and use it in GitHub Desktop.
Save sugilog/aea0c2a082e13b2b1e4d to your computer and use it in GitHub Desktop.
クロージャのスコープ
package main
import (
"fmt"
"math"
)
var k float64 = 1
func main() {
patternA()
patternB()
}
func patternA() {
f1 := newFunc()
f2 := newFunc()
f3 := newFunc()
fmt.Println( f1( 1 ) )
fmt.Println( f1( 1 ) )
fmt.Println( f2( 2 ) )
fmt.Println( f2( 2 ) )
fmt.Println( f3( 3 ) )
fmt.Println( f3( 3 ) )
fmt.Println( f1( 1 ) )
fmt.Println( f2( 2 ) )
fmt.Println( f3( 3 ) )
}
func newFunc() func( float64 ) float64 {
var j float64 = 1
return func( i float64 ) float64 {
fmt.Println( "**", i, j )
j = math.Pow( i, j )
return j
}
}
func patternB() {
f1 := newFuncWithOuterScope()
f2 := newFuncWithOuterScope()
f3 := newFuncWithOuterScope()
fmt.Println( f1( 1 ) )
fmt.Println( f1( 1 ) )
fmt.Println( f2( 2 ) )
fmt.Println( f2( 2 ) )
fmt.Println( f3( 3 ) )
fmt.Println( f3( 3 ) )
fmt.Println( f1( 1 ) )
fmt.Println( f2( 2 ) )
fmt.Println( f3( 3 ) )
}
func newFuncWithOuterScope() func( float64 ) float64 {
return func( i float64 ) float64 {
fmt.Println( "**", i, k )
k = math.Pow( i, k )
return k
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment