登录
首页 >  Golang >  Go问答

Wrapper for arbitrary function in Go

来源:Golang技术栈

时间:2023-04-14 06:57:29 341浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《Wrapper for arbitrary function in Go》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

问题内容

Is it possible to create a wrapper for arbitrary function in Go that would take the same arguments and return the same value?

I'm not talking about the wrapper that would look exactly the same, it may look differently, but it should solve the problem.

For example the problem might be to create a wrapper of arbitrary function that first looks for the result of the function call in cache and only in case of cache miss executes the wrapped function.

正确答案

The answer based on @joshlf13 idea and answer, but seems more simple to me. http://play.golang.org/p/v3zdMGfKy9

package main

import (
    "fmt"
    "reflect"
)

type (
    // Type of function being wrapped
    sumFuncT func(int, int) (int)

    // Type of the wrapper function
    wrappedSumFuncT func(sumFuncT, int, int) (int)
)

// Wrapper of any function
// First element of array is the function being wrapped
// Other elements are arguments to the function
func genericWrapper(in []reflect.Value) []reflect.Value {
    // this is the place to do something useful in the wrapper
    return in[0].Call(in[1:])
}

// Creates wrapper function and sets it to the passed pointer to function
func createWrapperFunction(function interface {}) {
    fn := reflect.ValueOf(function).Elem()
    v := reflect.MakeFunc(reflect.TypeOf(function).Elem(), genericWrapper)
    fn.Set(v)
}

func main() {
    var wrappedSumFunc wrappedSumFuncT

    createWrapperFunction(&wrappedSumFunc)

    // The function being wrapped itself
    sumFunc := func (a int, b int) int {
        return a + b
    }

    result := wrappedSumFunc(sumFunc, 1, 3)
    fmt.Printf("Result is %v", result)
}

文中关于golang的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Wrapper for arbitrary function in Go》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>