timthelion
timthelion

Reputation: 2727

How can I write DRY golang map manipulation functions

As far as I know, golang has no type variables. So how can I DRY out these two functions?

func merge_modes32(nm map[uint32]pb.Mode, om map[uint32]pb.Mode) {
    for k, v := range nm {
        om[k] = v
    }
}

func merge_modes64(nm map[uint64]pb.Mode, om map[uint64]pb.Mode) {
    for k, v := range nm {
        om[k] = v
    }
}

Upvotes: 1

Views: 144

Answers (1)

icza
icza

Reputation: 417662

You can't "dry" that in a way that will be close in performance. You could use reflection, but the resulting code will be drastically slower.

What to do? Until generics arrive (maybe in Go 2?), you may keep creating such functions for all required types, or just use the for loop where it's needed. It's just 3 lines of code including the loop and brackets...

Upvotes: 3

Related Questions