本文整理汇总了Golang中reflect.MakeFunc函数的典型用法代码示例。如果您正苦于以下问题:Golang MakeFunc函数的具体用法?Golang MakeFunc怎么用?Golang MakeFunc使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了MakeFunc函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TemplateVars
func TemplateVars(typ interface{}) template.VarMap {
fin := []reflect.Type{reflect.TypeOf(typ)}
stringOut := []reflect.Type{reflect.TypeOf("")}
stringFuncTyp := reflect.FuncOf(fin, stringOut, false)
varFunc := func(in []reflect.Value) []reflect.Value {
url, _ := updatesURL(in[0])
return []reflect.Value{reflect.ValueOf(url)}
}
boolOut := []reflect.Type{reflect.TypeOf(true)}
boolFuncTyp := reflect.FuncOf(fin, boolOut, false)
enabledFunc := func(in []reflect.Value) []reflect.Value {
url, _ := updatesURL(in[0])
enabled := url != ""
return []reflect.Value{reflect.ValueOf(enabled)}
}
template.AddFunc(&template.Func{
Name: "__gondola_is_live_reload_enabled",
Fn: reflect.MakeFunc(boolFuncTyp, enabledFunc).Interface(),
Traits: template.FuncTraitContext,
})
reasonFunc := func(in []reflect.Value) []reflect.Value {
_, reason := updatesURL(in[0])
return []reflect.Value{reflect.ValueOf(reason)}
}
template.AddFunc(&template.Func{
Name: "__gondola_is_live_reload_disabled_reason",
Fn: reflect.MakeFunc(stringFuncTyp, reasonFunc).Interface(),
Traits: template.FuncTraitContext,
})
return template.VarMap{
"BroadcasterWebsocketUrl": reflect.MakeFunc(stringFuncTyp, varFunc).Interface(),
}
}
示例2: MakeMockedWrapper
func MakeMockedWrapper(fptr interface{}) {
var maker = func(in []reflect.Value) []reflect.Value {
wrapper := in[0].Elem()
client := in[1]
wrapperType := wrapper.Type()
for i := 1; i < wrapperType.NumField(); i++ {
field := wrapper.Field(i)
fd, ok := client.Type().MethodByName(wrapperType.Field(i).Name)
if !ok {
logs.Info("Reflect Failed")
continue
}
fdt := fd.Type
f := reflect.MakeFunc(field.Type(), func(in []reflect.Value) []reflect.Value {
ret := make([]reflect.Value, 0, fdt.NumOut())
for i := 0; i < fdt.NumOut(); i++ {
ret = append(ret, reflect.Zero(fdt.Out(i)))
}
return ret
})
field.Set(f)
}
return []reflect.Value{in[0]}
}
fn := reflect.ValueOf(fptr).Elem()
v := reflect.MakeFunc(fn.Type(), maker)
fn.Set(v)
}
示例3: test16
func test16() {
defer mustRecover(16)
f2 := reflect.MakeFunc(reflect.TypeOf((func(func()))(nil)), reflectFunc2).Interface().(func(func()))
f3 := reflect.MakeFunc(reflect.TypeOf((func())(nil)), reflectFunc3).Interface().(func())
defer f2(f3)
panic(16)
}
示例4: Funcs
// Funcs allows creating functions for easily setting and retrieving
// values associated with a key from an Storage in a type safe manner.
//
// Getter functions must conform to the following specification:
//
// func(storage S, key interface{}) V or func(storage S, key interface{}) (V, bool)
//
// Where S is kvs.Storage or implements kvs.Storage and V is any type.
//
// Setter functions must conform to the following specification:
//
// func(storage S, key interface{}, value V)
//
// Where V is any type. Note that when generating a getter/setter function pair,
// V must be exactly the same type in the getter and in the setter.
//
// See the examples for more information.
//
// Note that this function will panic if the prototypes of the functions don't,
// match the expected ones.
//
// Alternatively, if you're only going to store once value per type, use
// TypeFuncs instead.
func Funcs(getter interface{}, setter interface{}) {
gptr := reflect.ValueOf(getter)
if gptr.Kind() != reflect.Ptr || gptr.Elem().Kind() != reflect.Func {
panic(fmt.Errorf("getter must be a pointer to a function, not %v",
gptr.Type()))
}
gval := gptr.Elem()
gvalType := gval.Type()
if gvalType.NumIn() != 2 {
panic(fmt.Errorf("getter must accept two arguments, not %d",
gvalType.NumIn()))
}
if !isStorageType(gvalType.In(0)) {
panic(fmt.Errorf("getter 1st argument must be of type %v or assignable to it, not %v",
storageType, gvalType.In(0)))
}
if gvalType.In(1) != emptyInterfaceType {
panic(fmt.Errorf("getter 2nd argument must be of type %v, not %v",
emptyInterfaceType, gvalType.In(1)))
}
if gvalType.NumOut() != 1 {
panic(fmt.Errorf("getter must return only one value, not %d",
gvalType.NumOut()))
}
ttype := gvalType.Out(0)
gval.Set(reflect.MakeFunc(gvalType, storageGetKey(ttype)))
sptr := reflect.ValueOf(setter)
if sptr.Kind() != reflect.Ptr || sptr.Elem().Kind() != reflect.Func {
panic(fmt.Errorf("setter must be a pointer to a function, not %v",
sptr.Type()))
}
sval := sptr.Elem()
svalType := sval.Type()
if svalType.NumIn() != 3 {
panic(fmt.Errorf("setter must accept three arguments, not %d",
svalType.NumIn()))
}
if !isStorageType(svalType.In(0)) {
panic(fmt.Errorf("setter's 1st argument must be of type %v or assignable to it, not %v",
storageType, svalType.In(0)))
}
if svalType.In(1) != emptyInterfaceType {
panic(fmt.Errorf("setter's 2nd argument must be of type %v, not %v",
emptyInterfaceType, svalType.In(1)))
}
if svalType.In(2) != ttype {
panic(fmt.Errorf("setter's 3rd argument must be of type %v (to match getter), not %v",
ttype, svalType.In(2)))
}
if svalType.NumOut() != 0 {
panic(fmt.Errorf("setter not return any values, not %d",
svalType.NumOut()))
}
sval.Set(reflect.MakeFunc(svalType, storageSetKey))
}
示例5: setTargetFn
func (self *GoSpy) setTargetFn(fn func(args []reflect.Value) []reflect.Value) {
targetType := self.mock.GetTarget().Type()
wrapperFn := func(args []reflect.Value) []reflect.Value {
self.storeCall(args)
return reflect.MakeFunc(targetType, fn).Call(args)
}
targetFn := reflect.MakeFunc(targetType, wrapperFn)
self.mock.Replace(targetFn.Interface())
}
示例6: makeSum
func makeSum(fptr interface{}) {
fn := reflect.ValueOf(fptr).Elem()
v := reflect.MakeFunc(fn.Type(), sum)
fn.Set(v)
}
示例7: compose
// compose modifies t such that it respects the previously-registered hooks in old,
// subject to the composition policy requested in t.Compose.
func (t *ClientTrace) compose(old *ClientTrace) {
if old == nil {
return
}
tv := reflect.ValueOf(t).Elem()
ov := reflect.ValueOf(old).Elem()
structType := tv.Type()
for i := 0; i < structType.NumField(); i++ {
tf := tv.Field(i)
hookType := tf.Type()
if hookType.Kind() != reflect.Func {
continue
}
of := ov.Field(i)
if of.IsNil() {
continue
}
if tf.IsNil() {
tf.Set(of)
continue
}
// Make a copy of tf for tf to call. (Otherwise it
// creates a recursive call cycle and stack overflows)
tfCopy := reflect.ValueOf(tf.Interface())
// We need to call both tf and of in some order.
newFunc := reflect.MakeFunc(hookType, func(args []reflect.Value) []reflect.Value {
tfCopy.Call(args)
return of.Call(args)
})
tv.Field(i).Set(newFunc)
}
}
示例8: One
// One wraps the given function to require one less argument, passing in the
// given value instead. The value MUST NOT be nil.
//
// BUG(abg): Variadic functions are not supported.
func One(f interface{}, a interface{}) interface{} {
if f == nil {
panic("f is required")
}
if a == nil {
panic("a is required and cannot be nil")
}
fType := reflect.TypeOf(f)
if fType.Kind() != reflect.Func {
panic(fmt.Sprintf("%v (%v) is not a function", f, fType))
}
if fType.IsVariadic() {
panic(fmt.Sprintf("%v (%v) is variadic", f, fType))
}
in := args(fType)
out := returns(fType)
if len(in) == 0 {
panic(fmt.Sprintf("%v (%v) does not accept enough arguments to curry in %v", f, fType, a))
}
fVal := reflect.ValueOf(f)
aVal := reflect.ValueOf(a)
newFType := reflect.FuncOf(in[1:], out, false)
return reflect.MakeFunc(newFType, func(args []reflect.Value) []reflect.Value {
newArgs := make([]reflect.Value, 0, fType.NumIn())
newArgs = append(newArgs, aVal)
newArgs = append(newArgs, args...)
return fVal.Call(newArgs)
}).Interface()
}
示例9: Open
// Open retrieves the symbols defined in plugin, from the shared library at path.
// path should omit the file extension (e.g. "plugin" instead of "plugin.so").
// plugin should be a pointer to a struct embedding the Plugin struct.
func Open(plugin interface{}, path string) error {
v := reflect.ValueOf(plugin)
t := v.Type()
if t.Kind() != reflect.Ptr {
return errors.New("Open expects a plugin to be a pointer to a struct")
}
v = v.Elem()
t = v.Type()
if t.Kind() != reflect.Struct {
return errors.New("Open expects a plugin to be a pointer to a struct")
}
lib, err := dl.Open(path, 0)
if err != nil {
return err
}
for i := 0; i < v.NumField(); i++ {
tf := t.Field(i)
if tf.Name != _plugin {
sym := v.Field(i).Interface()
if err := lib.Sym(tf.Name, &sym); err != nil && tf.Type.Kind() == reflect.Func {
fn := reflect.MakeFunc(tf.Type, nopFn)
v.Field(i).Set(fn)
} else {
v.Field(i).Set(reflect.ValueOf(sym))
}
} else {
p := Plugin{lib}
v.Field(i).Set(reflect.ValueOf(p))
}
}
return nil
}
示例10: function2Func
func function2Func(in *reflect.Value, t reflect.Type) {
fn := in.MethodByName("Call")
wrap := func(args []reflect.Value) (results []reflect.Value) {
ret := fn.Call(args)[0]
n := t.NumOut()
if n == 0 {
return
}
if n == 1 {
if t.Out(0) != typeIntf {
ret = ret.Elem()
}
return []reflect.Value{ret}
}
if ret.Kind() != reflect.Slice || ret.Len() != n {
panic(fmt.Sprintf("unexpected return value count, we need `%d` values", n))
}
results = make([]reflect.Value, n)
for i := 0; i < n; i++ {
result := ret.Index(i)
if t.Out(i) != typeIntf {
result = result.Elem()
}
results[i] = result
}
return
}
*in = reflect.MakeFunc(t, wrap)
}
示例11: getPluginProxy
func getPluginProxy(name string, extInterface interface{}) interface{} {
extInterfaceType := reflect.TypeOf(extInterface).Elem()
if !hasImplementation(name, extInterfaceType.Name()) {
return nil
}
pluginProxy := reflect.New(extInterfaceType).Elem()
// loop over fields defined in extInterfaceType,
// replacing them in v with implementations
for i, n := 0, extInterfaceType.NumField(); i < n; i++ {
field := pluginProxy.Field(i)
structField := extInterfaceType.Field(i)
newFunc := func(args []reflect.Value) []reflect.Value {
runner := plugin.loaded[name]
if runner == nil {
return []reflect.Value{reflect.ValueOf(nil)}
}
value, err := runner.CallPlugin(name, structField.Name, convertArgs(args))
if err != nil {
log.Println("plugins:", err)
}
if value != nil {
return []reflect.Value{reflect.ValueOf(value)}
}
return []reflect.Value{}
}
field.Set(reflect.MakeFunc(field.Type(), newFunc))
}
return pluginProxy.Interface()
}
示例12: main
func main() {
// swap is the implementation passed to MakeFunc.
// It must work in terms of reflect.Values so that it is possible
// to write code without knowing beforehand what the types
// will be.
swap := func(in []reflect.Value) []reflect.Value {
return []reflect.Value{in[1], in[0]}
}
// makeSwap expects fptr to be a pointer to a nil function.
// It sets that pointer to a new function created with MakeFunc.
// When the function is invoked, reflect turns the arguments
// into Values, calls swap, and then turns swap's result slice
// into the values returned by the new function.
makeSwap := func(fptr interface{}) {
// fptr is a pointer to a function.
// Obtain the function value itself (likely nil) as a reflect.Value
// so that we can query its type and then set the value.
fn := reflect.ValueOf(fptr).Elem()
// Make a function of the right type.
v := reflect.MakeFunc(fn.Type(), swap)
// Assign it to the value fn represents.
fn.Set(v)
}
// Make and call a swap function for ints.
var intSwap func(int, int) (int, int)
makeSwap(&intSwap)
fmt.Println(intSwap(0, 1))
// Make and call a swap function for float64s.
var floatSwap func(float64, float64) (float64, float64)
makeSwap(&floatSwap)
fmt.Println(floatSwap(2.72, 3.14))
}
示例13: JoinBy
// 连接函数 返回error 结束 下一次传递
func JoinBy(t interface{}, fs ...interface{}) interface{} {
val := reflect.ValueOf(t)
if val.Kind() != reflect.Func {
return nil
}
for k, v := range fs {
c := toCaller(v)
if c == nil {
return nil
}
fs[k] = c
}
typ := val.Type()
r := reflect.MakeFunc(typ, func(args []reflect.Value) (results []reflect.Value) {
inj := inject.New()
for _, v := range args {
inj.Set(v.Type(), v)
}
inj = SliceFunc(inj, fs)
for i := 0; i != typ.NumOut(); i++ {
results = append(results, inj.Get(typ.Out(i)))
}
return
})
return r.Interface()
}
示例14: MakeRpc
func (c *Client) MakeRpc(rpcName string, fptr interface{}) (err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("make rpc error")
}
}()
fn := reflect.ValueOf(fptr).Elem()
nOut := fn.Type().NumOut()
if nOut == 0 || fn.Type().Out(nOut-1).Kind() != reflect.Interface {
err = fmt.Errorf("%s return final output param must be error interface", rpcName)
return
}
_, b := fn.Type().Out(nOut - 1).MethodByName("Error")
if !b {
err = fmt.Errorf("%s return final output param must be error interface", rpcName)
return
}
f := func(in []reflect.Value) []reflect.Value {
return c.call(fn, rpcName, in)
}
v := reflect.MakeFunc(fn.Type(), f)
fn.Set(v)
return
}
示例15: GetProxy
func (p *AOP) GetProxy(beanID string) (proxy *Proxy, err error) {
var bean *Bean
if bean, err = p.beanFactory.GetBean(beanID); err != nil {
return
}
tmpProxy := NewProxy(beanID)
beanValue := reflect.ValueOf(bean.instance)
beanType := reflect.TypeOf(bean.instance)
for i := 0; i < beanValue.NumMethod(); i++ {
methodV := beanValue.Method(i)
methodT := beanType.Method(i)
mType := methodV.Type()
var metadata MethodMetadata
if metadata, err = getMethodMetadata(methodT); err != nil {
return
}
newFunc := p.funcWrapper(bean, metadata.Method.Name, mType)
funcV := reflect.MakeFunc(mType, newFunc)
metadata.Method.Func = funcV // rewrite to new proxy func
tmpProxy.registryFunc(metadata)
}
proxy = tmpProxy
return
}