Golang程序 检查一个值是否存在于哈希集合中 您所在的位置:网站首页 字母矩阵计算器 Golang程序 检查一个值是否存在于哈希集合中

Golang程序 检查一个值是否存在于哈希集合中

2023-03-30 01:49| 来源: 网络整理| 查看: 265

Golang程序 检查一个值是否存在于哈希集合中

在Golang中,我们可以通过简单地使用okidiom函数来检查一个给定的值是否存在于哈希集合中,或者我们甚至可以创建一个if-else用户定义的函数来做同样的事情。Hashmap基本上是一个值的集合,与它们在哈希集合中的键配对。在这篇文章中,我们将通过两个不同的例子来了解我们如何使用上述两种技术来检查哈希集合中的给定值。

算法 创建一个包main,并在程序中声明fmt(格式化包),其中main产生可执行代码,fmt帮助格式化输入和输出。

使用map literal创建一个哈希图,其中键是字符串类型的,值是int类型的。

将所需的值分配给键。

在这一步中,使用ok成语来检查地图中是否存在某个特定的键,如果存在,也可以得到其相应的值。

然后,如果该值存在于地图中,ok将被设置为true,并打印出成功声明。

如果值不存在,ok将被设置为false,并打印出失败语句。

打印语句是通过fmt包中的Println()函数执行的,其中ln表示新行。

例1

在这个例子中,我们将在map字面的帮助下创建一个hashmap。然后,借助ok这个成语,我们将查看键是否存在,如果键存在,它的对应值是否存在?如果输出为真,则打印成功声明,否则打印失败声明。

//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成语,它进一步指向真或假,表明该值是否存在,而在第二个例子中,我们使用了条件语句来执行程序。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有