Home  >  Article  >  Backend Development  >  Check for duplicate keys in different Go Map types

Check for duplicate keys in different Go Map types

WBOY
WBOYforward
2024-02-06 10:21:091018browse

检查不同 Go Map 类型中的重复键

Question content

I want a function to check for duplicate keys in different maps.

This is what I have

ma := map[string]typea
mb := map[string]typeb
mc := map[string]typec

dup := map[string]bool{}
    for k := range ma{
        if !dup[k] {
            dup[k] = true
        } else {
            return fmt.errorf("duplicate key[%v]", k)
        }
    }
    for k := range mb{
        if !dup[k] {
            dup[k] = true
        } else {
            return fmt.errorf("duplicate key[%v]", k)
        }
    }
    for k := range mc {
        if !dup[k] {
            dup[k] = true
        } else {
            return fmt.errorf("duplicate key[%v]", k)
        }
    }
    return nil

I want to refactor it and write a function

func checkDupKeys[M ~map[K]V, K comparable, V any](maps ...M) error {
    dup := map[K]bool{}
    for _, m := range maps {
        for k := range m {
            if !dup[k] {
                dup[k] = true
            } else {
                return fmt.Errorf("duplicate key[%v]", k)
            }
        }
    }
    return nil
}

But it can only accept mappings of the same type, not typea, typeb and typec.


Correct answer


You can try using any types and reflection

func checkDupKeys(maps ...any) error {
    dup := map[any]bool{}
    for i, m := range maps {
        t := reflect.TypeOf(m)
        if t.Kind() != reflect.Map {
            return fmt.Errorf("not a map at index: %d", i)
        }
        keys := reflect.ValueOf(m).MapKeys()
        for _, k := range keys {
            v := k.Interface()
            if !dup[v] {
                dup[v] = true
            } else {
                return fmt.Errorf("duplicate key[%v]", v)
            }
        }
    }
    return nil
}

The disadvantage of this approach is that the function will also accept non-mapped parameters, and the compiler will not warn about this.

The above is the detailed content of Check for duplicate keys in different Go Map types. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete