Go中的任意函数的包装器 [英] Wrapper for arbitrary function in Go

查看:88
本文介绍了Go中的任意函数的包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能为Go中的任意函数创建一个包装,它将采用相同的参数并返回相同的值?



我不是在谈论包装看起来完全一样,看起来可能不一样,但它应该可以解决问题。例如,问题可能是创建一个任意函数的包装,它首先看起来像对于缓存中的函数调用的结果,只有在缓存未命中的情况下执行包装函数。 解决方案

@ joshlf13的想法和答案,但对我来说似乎更简单。
http://play.golang.org/p/v3zdMGfKy9

 包裹主要

进口(
fmt
反映


类型(
//被包装函数的类型
sumFuncT func(int,int)(int)

//包装的类型函数
wrappedSumFuncT func(sumFuncT,int,int)(int)


//包装任何函数
//数组的第一个元素是函数包装
//其他元素是函数的参数
func genericWrapper(in [] reflect.Value)[] reflect.Value {
//这是在包装
返回[0] .Call(in [1:])
}

//创建包装函数并将其设置为函数
的传递指针func createWrapperFunction(function interface {}){
fn:= reflect.ValueOf(function).Elem()
v:= reflect.MakeFunc(reflect.TypeOf(function).Elem(),gene ricWrapper)
fn.Set(v)
}

func main(){
var wrappedSumFunc wrappedSumFuncT

createWrapperFunction(&wrappedSumFunc )

//被包装的函数
sumFunc:= func(int,b int)int {
return a + b
}

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


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)
}

这篇关于Go中的任意函数的包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆