Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

Idiom #52 Check if map contains value

Determine whether the map m contains an entry with the value v, for some key.

Is this value contained in this map, for any key?
func containsValue(m map[K]T, v T) bool {
	for _, x := range m {
		if x == v {
			return true
		}
	}
	return false
}

You have to iterate explicitly. In this implementation, the types K, T are not generic.
func containsValue[M ~map[K]V, K, V comparable](m M, v V) bool {
	for _, x := range m {
		if x == v {
			return true
		}
	}
	return false
}

This generic function works for any type parameters K, V that are comparable
(boolean (some #{v} (vals m)))

In Clojure values are truthy/falsy

no need for boolean, however included due to other language examples

New implementation...