Go map of functions

前端 未结 6 1535
春和景丽
春和景丽 2020-12-23 09:21

I have Go program that has a function defined. I also have a map that should have a key for each function. How can I do that?

I have tried this, but this doesn\'t wo

6条回答
  •  悲&欢浪女
    2020-12-23 10:06

    I used a map[string]func (a type, b *type) I passed a string to search the map and a pointer to modify the slice.

    Hope that helps!

    var Exceptions map[string]func(step string, item *structs.Item)
    
    func SetExceptions() {
        Exceptions = map[string]func(a string, i *structs.Item){
            "step1": step1,
        }
    }
    
    func RunExceptions(state string, item *structs.Item) {
        method, methBool := Exceptions[state]
        if methBool {
            method(state, item)
        }
    }
    
    func step1(step string, item *structs.Item) {
        item.Title = "Modified"
    }
    

提交回复
热议问题