Last active
June 12, 2019 03:38
-
-
Save guerbai/6bd7d07c0edcf959a8fd9bba6697e33c to your computer and use it in GitHub Desktop.
calculate函数,闭包与传函数
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
type operate func(x, y int) int | |
func calculate(x int, y int, op operate) (int, error) { | |
if op == nil { | |
return 0, error.New("no op") | |
} | |
return op(x, y), nil | |
} | |
var add = func (x, y int) int { | |
return x + y | |
} | |
v, _ := operate(1, 2, add) | |
fmt.Printf(v) |
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
func genCalculator(op operate) operate { | |
return func(x, y int) int { | |
return op(x, y) | |
} | |
} | |
add := genCalculator(func(x, y) int { | |
return x + y | |
}) | |
v := add(5, 6) | |
fmt.Println(v) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment