golang学习笔记---函数示例

package main

import (
    "fmt"
    "math"
    "reflect"
    "runtime"
)

func apply(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 pow(a, b int) int {
    return int(math.Pow(float64(a), float64(b)))
}
func main() {

    fmt.Println(apply(pow, 3, 4))

}

输出:

Calling function main.pow with args(3,4)81

package main

import (
    "fmt"
    "math"
    "reflect"
    "runtime"
)

func apply(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 main() {

    fmt.Println(apply(func(a, b int) int {
        return int(math.Pow(
            float64(a), float64(b)))
    }, 3, 4))

}

输出:

Calling function main.main.func1 with args(3,4)81

第一个main是包名,第二main是指main函数

 

posted on 2020-09-04 10:54  清明-心若淡定  阅读(219)  评论(0编辑  收藏  举报