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