Go語言程式檢查雜湊集合中是否存在給定鍵


在 Go 語言中,我們有像 ok 成語這樣的內建函式來檢查給定的鍵是否存在於雜湊集合中。雜湊圖是雜湊圖集合中成對的鍵值對。在本文中,我們將使用內建函式建立一個雜湊圖,然後我們將使用返回真假值的 ok 成語來檢查鍵是否存在於對映中。這樣就會打印出成功或失敗的語句。

演算法

  • 建立一個 package main 並宣告程式中的 fmt(格式包),其中 main 生成可執行程式碼,fmt 幫助格式化輸入和輸出。

  • 建立一個 main 函式,並在同一個函式中使用 map 建立一個雜湊圖,其中鍵的型別為字串,值的型別為整數。

  • 現在,分配 key=item2 並使用 ok 成語和索引檢查特定鍵是否存在於對映中。

  • 如果 ok 為真,則列印成功語句,否則列印失敗語句。

  • 在此步驟中,我們將重複步驟 3,但這次使用對映中不存在的另一個鍵,即 item4。

  • 我們將使用 ok 成語來檢查鍵是否存在於對映中,因為這裡的 ok 將為假,所以將列印失敗語句。

  • 輸出將使用 fmt 包中的 Println 函式反映在控制檯上,其中 ln 表示換行。

示例

使用 ok 成語函式檢查給定鍵是否存在於雜湊集合中的 Go 語言程式

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 成語來執行程式。程式執行成功。

更新於: 2023年3月27日

97 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.