Home > Software engineering >  golang how can I use struct name as map key
golang how can I use struct name as map key

Time:09-17

type A struct {
    a1 int
    a2 string
}
type B struct {
    b1 int
    b2 string
}
type C struct {
    c1 int
    c2 string
}

there are 3 structs, I want put the names into a map as key, and process func as map value

(instead of type-switch)

input arg is a interface, use for loop to judge what struct this interface is. And process this arg by process func in map value. about:

var funcMap map[structName]func(arg){A:processA, B:processB, C:processC}

func testFunc(arg) {
    for k, v in range funcMap {
        if k == reflect.TypeOf(arg) {
            v(arg)
        }
    }
} 

how can I build this map??? hope code, thanks! (^o^)

CodePudding user response:

You want to index your map on reflect.Type:

type funcMapType map[reflect.Type]func(interface{})

var funcMap funcMapType

then to register a type with a function:

funcMap[reflect.TypeOf(A{})] = func(v interface{}) { log.Println("found A") }

if your function needs to modify the struct, you'll need to register a pointer to the struct type:

funcMap[reflect.TypeOf(&A{})] = func(v interface{}) { log.Println("found *A") }

https://play.golang.org/p/LKramgSc_gz

  •  Tags:  
  • go
  • Related