• go通过名称来调用对应的方法


    仅仅是为了学习go语言中的反射。

    package main
    
    import (
    	"errors"
    	"fmt"
    	"reflect"
    )
    
    func Call(m map[string]interface{}, name string, params ...interface{}) ([]reflect.Value,error) {
    	_, found := m[name]
    	if !found {
    		return nil, errors.New("map do not contains key ...")
    	}
    	fv := reflect.ValueOf(m[name])
    	if fv.Kind() != reflect.Func {
    		return nil, errors.New("the value of key is not a function")
    	}
    
    	if len(params) != fv.Type().NumIn() {
    		return nil, errors.New("argument passed in does not match the function")
    	}
    
    	in := make([]reflect.Value, len(params))
    	// for i := 0; i < len(params); i++ {
    	// 	in[i] = reflect.ValueOf(params[i])
    	// }
    	for i, param := range params {
    		in[i] = reflect.ValueOf(param)
    	}
    	return fv.Call(in), nil
    }
    
    func test1(name string) {
    	fmt.Printf("hello,%s 
    ", name)
    }
    
    func test2(name string, age int) {
    	fmt.Printf("hello,my name is %s ,%d years old", name, age)
    }
    
    func main() {
    	m := make(map[string]interface{})
    	m["test1"] = test1
    	m["test2"] = test2
    
    	result, err := Call(m, "test2", "hupeng", 12)
    	if err != nil {
    		panic(err)
    	}
    	fmt.Println(result)
    
    }
    
    
  • 相关阅读:
    C++范围解析运算符::的使用
    C程序的内存布局
    ARM中LDR伪指令与LDR加载指令
    每天一个linux命令(12):more命令
    C++ explicit关键字
    C++内联函数详解
    C++友元详解
    C++ new操作符详解
    CDN技术详解笔记
    字符串匹配(KMP 算法 含代码)
  • 原文地址:https://www.cnblogs.com/hupengcool/p/4128522.html
Copyright © 2020-2023  润新知