Check for duplicate keys in different Go Map types

WBOY
Release: 2024-02-06 10:21:09
forward
1044 people have browsed it

检查不同 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
Copy after login

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
}
Copy after login

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
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!