Created
January 4, 2015 12:35
-
-
Save sugilog/aea0c2a082e13b2b1e4d to your computer and use it in GitHub Desktop.
クロージャのスコープ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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