惜风不起、唯有努力!
go闭包实现加、减、乘、除运算小示例

go闭包实现加、减、乘、除运算小示例

package main

import(
	"fmt"
)

func arithmeticOperation(op string) func(int) int {
	switch op {
	case "+":
	  return func(i int) int {
		return i + 10
	  }
	case "-":
	  return func(i int) int {
		return i - 10
	  }
	case "*":
	  return func(i int) int {
		return i * 10
	  }
	case "/":
	  return func(i int) int {
		return i / 10
	  }
	default:
	  return func(i int) int {
		return i
	  }
	}
  }
  
  func main() {
	add := arithmeticOperation("+")
	fmt.Println(add(5)) // 15
  
	sub := arithmeticOperation("-")
	fmt.Println(sub(5)) // -5
  
	mul := arithmeticOperation("*")
	fmt.Println(mul(5)) // 50
  
	div := arithmeticOperation("/")
	fmt.Println(div(5)) // 0
  
	noOp := arithmeticOperation("unknown")
	fmt.Println(noOp(5)) // 5
  }

发表回复

您的电子邮箱地址不会被公开。