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

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

在Golang中,我们可以通过使用ok惯用语法函数或者创建一个自定义的if-else函数来检查一个给定的值是否存在于哈希集合中。哈希映射是一组将值与其在哈希集合中的键配对的集合。在本文中,我们将通过两个不同的示例来了解如何使用上述两种技术来检查哈希集合中的给定值。

步骤

  • 在程序中创建一个package main并声明fmt(格式化包),其中main生成可执行代码,而fmt用于格式化输入和输出。

  • 使用map字面量创建一个哈希映射,其中键的类型为string,值的类型为int。

  • 为键分配所需的值。

  • 在这一步中,使用ok惯用语法检查地图中是否存在特定的键,如果存在,则相应的值也可以被获取。

  • 然后,如果值存在于映射中,则ok将被设置为true并打印成功语句。

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

  • 使用fmt包中的Println()函数执行打印语句,其中ln表示新行。

示例1

在这个示例中,我们将使用map字面量来创建一个哈希映射。然后,借助ok惯用语法,我们将看到键是否存在,如果键存在,对应的值是否也存在?如果输出为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习语,进一步指示值是否存在(真或假),而在第二个示例中,我们使用条件语句来执行程序。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程