0
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^)

0

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

for other readers: don't forget that reflect.TypeOf(A{}) != reflect.TypeOf(&A{}). Types must be identical
how to handle pointer to struct as key? example: *A?
@xiangyuhaoaizcm updated answer & playground-link with pointer logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.