Go语言程序检查哈希集合中是否存在给定键


在 Go 语言中,我们有像 ok 成语这样的内置函数来检查给定的键是否存在于哈希集合中。哈希图是哈希图集合中成对的键值对。在本文中,我们将使用内置函数创建一个哈希图,然后我们将使用返回真假值的 ok 成语来检查键是否存在于映射中。这样就会打印出成功或失败的语句。

算法

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

  • 创建一个 main 函数,并在同一个函数中使用 map 创建一个哈希图,其中键的类型为字符串,值的类型为整数。

  • 现在,分配 key=item2 并使用 ok 成语和索引检查特定键是否存在于映射中。

  • 如果 ok 为真,则打印成功语句,否则打印失败语句。

  • 在此步骤中,我们将重复步骤 3,但这次使用映射中不存在的另一个键,即 item4。

  • 我们将使用 ok 成语来检查键是否存在于映射中,因为这里的 ok 将为假,所以将打印失败语句。

  • 输出将使用 fmt 包中的 Println 函数反映在控制台上,其中 ln 表示换行。

示例

使用 ok 成语函数检查给定键是否存在于哈希集合中的 Go 语言程序

Open Compiler
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) } }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

Item 'item2' exists in the hash collection.
Item'item4' does not exist in the hash collection.

结论

我们执行了程序以检查给定键是否存在于哈希集合中,使用了一个示例,其中我们使用 ok 成语来执行程序。程序执行成功。

更新于: 2023年3月27日

97 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告