mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-15 18:22:27 +08:00
feat: add HasKey
This commit is contained in:
@@ -289,3 +289,21 @@ func MapValues[K comparable, V any, T any](m map[K]V, iteratee func(key K, value
|
|||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// HasKey checks if map has key or not.
|
||||||
|
// This function is used to replace the following boilerplate code:
|
||||||
|
// _, haskey := amap["baz"];
|
||||||
|
//
|
||||||
|
// if haskey {
|
||||||
|
// fmt.Println("map has key baz")
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// Play: todo
|
||||||
|
func HasKey[K comparable, V any](m map[K]V, key K) bool {
|
||||||
|
_, haskey := m[key]
|
||||||
|
if haskey {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|||||||
@@ -433,3 +433,20 @@ func ExampleMapTo() {
|
|||||||
// <nil>
|
// <nil>
|
||||||
// {Nothin 28 123456789 {test 1}}
|
// {Nothin 28 123456789 {test 1}}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ExampleHasKey() {
|
||||||
|
m := map[string]int{
|
||||||
|
"a": 1,
|
||||||
|
"b": 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
result1 := HasKey(m, "a")
|
||||||
|
result2 := HasKey(m, "c")
|
||||||
|
|
||||||
|
fmt.Println(result1)
|
||||||
|
fmt.Println(result2)
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// true
|
||||||
|
// false
|
||||||
|
}
|
||||||
|
|||||||
@@ -458,3 +458,17 @@ func TestMapValues(t *testing.T) {
|
|||||||
|
|
||||||
assert.Equal(expected, result)
|
assert.Equal(expected, result)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestHasKey(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
assert := internal.NewAssert(t, "TestHasKey")
|
||||||
|
|
||||||
|
m := map[string]int{
|
||||||
|
"a": 1,
|
||||||
|
"b": 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.Equal(true, HasKey(m, "a"))
|
||||||
|
assert.Equal(false, HasKey(m, "c"))
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user