A piece of code that combines golang reflection and functions

Determine the calling method based on reflection,
poll the map to determine the method call,
with return value

In order to realize the reflection-based class operation and processing method,
if class A, then method A,
if class B, then method B
...
Compared to switch, we can use map m as a global variable to realize variable injection

package main

import (
	"fmt"
	"reflect"
)

func goFunc2(f func(interface{
    
    }), i interface{
    
    }) {
    
    
	f(i)
}

func DoString(i interface{
    
    }) string {
    
    
	return "str " + i.(string)
}

func DoOthers(i interface{
    
    }) {
    
    
	fmt.Println("default")
}

func f2(i interface{
    
    }) {
    
    
	var m map[reflect.Type]func(interface{
    
    }) string
	m = make(map[reflect.Type]func(interface{
    
    }) string)
	m[reflect.TypeOf("")] = DoString
	for k, v := range m {
    
    
		if k == reflect.TypeOf(i) {
    
    
			fmt.Println(v(i))
		}
	}
	fmt.Println("f2 done", i)
}

func main() {
    
    
	goFunc2(f2, 100)
	goFunc2(f2, "abc")
}
 go run main.go
f2 done 100
str abc
f2 done abc

Guess you like

Origin blog.csdn.net/oe1019/article/details/120926879