1 package main 2 3 import ( 4 "fmt" 5 "reflect" 6 "runtime" 7 "math" 8 ) 9 10 //函数 11 //函数可以返回两个值。返回多个值时可以起名字 12 //返回值类型写在最后面 13 //函数可以作为参数 14 //没有默认参数,可选参数 15 16 func eval( a, b int , op string) ( int , error) { 17 switch op { 18 case "+": 19 return a + b , nil 20 case "-": 21 return a - b , nil 22 case "*": 23 return a * b , nil 24 case "/": 25 q, _ := div(a , b) //下划线表示不想用那个返回值 26 return q , nil 27 default: 28 return 0 , fmt.Errorf("unsupported operation: %s" , op ) 29 } 30 } 31 32 func div( a, b int ) ( int , int) { 33 return a / b, a % b 34 } 35 36 func apply( op func( int , int ) int , a, b int ) int { //参数名写在前,类型写在后 37 p := reflect.ValueOf(op).Pointer() 38 opName := runtime.FuncForPC(p).Name() 39 fmt.Printf("calling function %s with agrs" + "(%d,%d) ",opName,a,b) 40 return op(a , b) 41 } 42 43 func pow( a, b int) int { 44 return int (math.Pow( float64(a),float64(b))) 45 } 46 47 func sum( numbers ...int) int { //...传可变参数列表 48 s := 0 49 for i := range numbers { 50 s += numbers[i] 51 } 52 return s 53 } 54 func main() { 55 if result , err := eval( 3,4,"x"); err != nil { 56 fmt.Println("Error",err) //Error unsupported operation: x 57 }else { 58 fmt.Println(result) 59 } 60 fmt.Println(eval(3, 4, "*")) // 12 <nil> 61 fmt.Println(eval(3, 4, "/")) // 0 <nil> 62 fmt.Println( div(13 , 3)) // 4 1 63 fmt.Println(apply( pow,3,4)) //calling function main.pow with agrs(3,4) 81 64 65 fmt.Println(apply( 66 func(a int, b int) int { 67 return int( math.Pow( 68 float64(a), float64(b) )) 69 },3,4, 70 )) //calling function main.main.func1 with agrs(3,4) 81 71 72 fmt.Println(sum(1,2,3,4,5)) //15 73 }