diff --git a/docs/maputil.md b/docs/maputil.md index fbcc6f5..7bd7b2c 100644 --- a/docs/maputil.md +++ b/docs/maputil.md @@ -43,6 +43,7 @@ import ( - [Merge](#Merge) - [Minus](#Minus) - [IsDisjoint](#IsDisjoint) +- [HasKey](#HasKey)
@@ -893,7 +894,7 @@ func main() { ### IsDisjoint -Checks two maps are disjoint if they have no keys in common
+Checks two maps are disjoint if they have no keys in common.
Signature: @@ -937,3 +938,49 @@ func main() { // false } ``` + +### HasKey + +Checks if map has key or not. This function is used to replace the following boilerplate code:
+ +```go +_, haskey := amap["baz"]; + +if haskey { + fmt.Println("map has key baz") +} +``` + +Signature: + +```go +func HasKey[K comparable, V any](m map[K]V, key K) bool +``` + +Example: + +```go +package main + +import ( + "fmt" + "github.com/duke-git/lancet/v2/maputil" +) + +func main() { + 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 +} +``` diff --git a/docs/maputil_zh-CN.md b/docs/maputil_zh-CN.md index dc012c5..f578d78 100644 --- a/docs/maputil_zh-CN.md +++ b/docs/maputil_zh-CN.md @@ -43,6 +43,7 @@ import ( - [Merge](#Merge) - [Minus](#Minus) - [IsDisjoint](#IsDisjoint) +- [HasKey](#HasKey) @@ -932,3 +933,49 @@ func main() { // false } ``` + +### HasKey + +检查map是否包含某个key。用于代替以下样板代码:
+ +```go +_, haskey := amap["baz"]; + +if haskey { + fmt.Println("map has key baz") +} +``` + +函数签名: + +```go +func HasKey[K comparable, V any](m map[K]V, key K) bool +``` + +示例: + +```go +package main + +import ( + "fmt" + "github.com/duke-git/lancet/v2/maputil" +) + +func main() { + 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 +} +```