Skip to content

proposal: maps: add function to check existence of a key #67377

Open
@gudvinr

Description

@gudvinr

Proposal Details

A lot of code uses pattern like this:

if _, ok := somemap[somekey]; ok {
    ...
}

just to check if key exists in a map.

And, with *Func functions from strings, slices, etc packages it makes code look unnecessary ugly.
For example, to filter out elements of a slice that exist in a map you need to do this:

type Buzz struct {
    ID string
}

var fizzies map[string]int
var buzzies []Buzz

...

buzzies = slices.DeleteFunc(buzzies, func (buzz Buzz) bool {
    _, ok := fizzies[buzz.ID]
    return ok
})

Instead of, let's say, this:

buzzies = slices.DeleteFunc(buzzies, func (buzz Buzz) bool {
    return maps.Contains(fizzies, buzz.ID)
})

That might be subjective, but one-line return statement looks less clunky.

I deliberately used this example because simple one, with var buzzies []string might raise unnecessary questions like "why not add something like HasKeyFunc(map[K]V) func(K) bool" which will make this example look like this:

buzzies = slices.DeleteFunc(buzzies, maps.HasKeyFunc(fizzies))

Which looks pretty, but doesn't make other cases any more readable than first example.

Bike-shedding section

I don't care about naming, but already implied maps.Contains because it's common across std.

One might argue that semantics of e.g. slices.Contains differ from maps.Contains because slices.Contains uses slice values instead of indices.
But there is an opposite argument of delete(map, key) that follows this pattern for maps while slices.Delete uses indices instead of values.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions