golang 函数
可变参数列表
//可变参数 func sum(numbers ...int) int { s := 0 for i := range numbers { s += numbers[i] } return s }
package main import ( "fmt" "math" "reflect" "runtime" ) //返回一个参数 func eval(a, b int, op string) (int, error) { switch op { case "+": return a + b, nil case "-": return a - b, nil case "*": return a * b, nil case "/": return a / b, nil default: //panic 主动输出错误,中断程序 //panic("unsupported operation: " + op) return 0, fmt.Errorf("unsupported operation: %s", op) } } //返回多个参数 func dic(a, b int) (int, int) { return a / b, a % b } //函数式编程 func fcunApply(op func(int, int) int, a, b int) int { p := reflect.ValueOf(op).Pointer() opName := runtime.FuncForPC(p).Name() fmt.Printf("Calling function %s with args " + "(%d, %d) ", opName, a, b) return op(a, b) } // func power(a, b int) int { return int(math.Pow(float64(a), float64(b))) } func main() { if result, err := eval(1, 2, "+"); err != nil { fmt.Println(err) } else { fmt.Println(result) } fmt.Println(eval(1, 2, "+a")) a, b := dic(13, 4) fmt.Println(a, b) fmt.Println(fcunApply(power, 3, 4)) //匿名函数 fmt.Println(fcunApply( func(a int, b int) int { return int(math.Pow( float64(3), float64(4))) }, 3, 4)) }