Go语言程序用于检查哈希集合中是否存在值
在 Go 语言中,我们可以通过简单的 ok-idiom 函数来检查给定值是否存在于哈希集合中,或者我们可以创建一个 if-else 用户自定义函数来实现相同的功能。哈希映射 (HashMap) 本质上是一个键值对的集合。在本文中,我们将通过两个不同的示例来了解如何使用以上两种技术来检查哈希集合中是否存在给定值。
算法
创建一个 `main` 包,并在程序中声明 `fmt`(格式化包),其中 `main` 生成可执行代码,`fmt` 帮助格式化输入和输出。
使用映射字面量创建一个哈希映射,其中键的类型为字符串,值的类型为整数。
为键分配所需的值。
在此步骤中,使用 ok-idiom 来检查特定键是否存在于映射中,如果存在,还可以获得其对应的值。
如果值存在于映射中,则 ok 将被设置为 true,并打印成功语句。
如果值不存在,则 ok 将被设置为 false,并打印失败语句。
使用 `fmt` 包中的 `Println()` 函数执行打印语句,其中 `ln` 表示换行。
示例 1
在这个例子中,我们将使用映射字面量创建一个哈希映射。然后,我们将使用 ok-idiom 来查看键是否存在,如果键存在,其对应的值是否存在?如果输出为 true,则打印成功语句;否则打印失败语句。
//Golang program to check if a value exists in the hash collection or not
package main
import "fmt"
//Main function to execute the program
func main() {
// create a hashmap with key:value pairs
hashmap := map[string]int{
"pencil": 10,
"pen": 20,
"scale": 15,
}
fmt.Println("Whether the value exists in the map?") //if the value exists print if statement else print else statement
if _, ok := hashmap["pencil"]; ok {
fmt.Println("The value exists in the hash collection.")
} else {
fmt.Println("The value does not exist in the hash collection.")
}
}
输出
Whether the value exists in the map? The value exists in the hash collection.
示例 2
在这个例子中,我们将创建一个哈希映射并对其进行迭代,使用条件 if-else 语句检查值是否存在于其中。如果条件满足,则打印并返回成功语句;否则打印失败语句。
//Golang program to check a value exists in the hash collection or not
package main
import (
"fmt"
)
//Main function to execute the program
func main() {
// create a hashmap with key:value pairs
hashmap := map[string]string{
"item1": "value1",
"item2": "value2",
"item3": "value3",
}
// check if a value exists in the hash collection
fmt.Println("Whether the value exists in the map?")
value := "value2"
for _, v := range hashmap {
if v == value {
fmt.Println("Value exists in the hash collection")
return
}
}
fmt.Println("Value does not exist in the hash collection")
}
输出
Whether the value exists in the map? Value exists in the hash collection
结论
我们通过两个示例执行了这个检查哈希集合中是否存在值的程序。在第一个示例中,我们使用了 ok-idiom,它进一步指向 true 或 false,表示值是否存在;而在第二个示例中,我们使用了条件语句来执行程序。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP