Collection of Unique Functions in Go

前端 未结 2 1331
野趣味
野趣味 2021-01-24 16:00

I am trying to implement a set of functions in go. The context is an event server; I would like to prevent (or at least warn) adding the same handler more than once for an even

2条回答
  •  走了就别回头了
    2021-01-24 16:27

    Which functions you mean to be equal? Comparability is not defined for functions types in language specification. reflect.Value gives you the desired behaviour more or less

    type EventResponseSet map[reflect.Value]struct{}
    set := make(EventResponseSet)
    if _, ok := set[reflect.ValueOf(item)]; ok {
        // don't add item
    } else {
        // do add item
        set[reflect.ValueOf(item)] = struct{}{}
    }
    

    this assertion will treat as equal items produced by assignments only

    //for example
    item1 := fmt.Println
    item2 := fmt.Println
    item3 := item1
    //would have all same reflect.Value
    

    but I don't think this behaviour guaranteed by any documentation.

提交回复
热议问题