Golang 检查哈希集合中给定的键是否存在
在Golang中,我们有内置的ok习惯用法函数,用于检查哈希集合中是否存在给定的键。哈希映射是一个由键值对组成的集合。在本文中,我们将使用内置函数创建一个哈希映射,然后我们将使用ok习惯用法来检查键是否存在于映射中。以此方式,将打印成功或失败的语句。
步骤
- 在程序中创建一个main包,并声明fmt格式包,其中main产生可执行代码,fmt帮助格式化输入和输出。
-
创建一个main函数,在相同的函数中使用map创建一个哈希映射,其中键的类型为字符串,值的类型为int。
-
现在,将键分配为item2,并使用ok习惯用法和索引检查该键是否存在于映射中。
-
如果ok为真,则打印成功的语句,否则打印失败的语句。
-
在此步骤中,我们将重复步骤3,但这次使用映射中不存在的另一个键,即item4。
-
我们将使用ok习惯用法来检查键是否存在于映射中,因为此处ok为假,因此会打印失败的语句。
-
输出将使用fmt包的Println函数在控制台上反映出来,其中ln表示换行。
示例
使用ok习惯用法函数检查哈希集合中是否存在给定的键的Golang程序
package main
import "fmt"
//Main function to execute the program
func main() {
// create a hash collection
hashmap := map[string]string{
"item1": "value1",
"item2": "value2",
"item3": "value3",
}
// check if a key exists in the hashmap
key := "item2"
if _, ok := hashmap[key]; ok {
fmt.Printf("Item '%s' exists in the hash collection.\n", key)
} else {
fmt.Printf("item '%s' does not exist in the hash collection.\n", key)
}
// check if this key exists in the map or not (not found)
key = "item4"
if _, ok := hashmap[key]; ok {
fmt.Printf("Item '%s' exists in the hash collection.\n", key)
} else {
fmt.Printf("Item'%s' does not exist in the hash collection.\n", key)
}
}
输出
Item 'item2' exists in the hash collection.
Item'item4' does not exist in the hash collection.
结论
我们执行了程序,检查散列集合中是否存在给定的键,使用一个示例,在其中我们使用“ok习惯用法”来执行程序。程序成功执行。