基於指定鍵從雜湊集合中獲取值的 Go 語言程式
在這篇 Go 語言文章中,我們將編寫 Go 語言程式,使用 `found` 變數以及 `ok` 判斷法從雜湊集合中基於指定鍵獲取值。
雜湊對映是一種屬於雜湊集合的資料結構。它以鍵值對的形式儲存資料。
語法
func make ([] type, size, capacity)
Go 語言中的 `make` 函式用於建立陣列/對映,它接受要建立的變數型別、大小和容量作為引數。
演算法
步驟 1 − 此程式匯入兩個包 `fmt` 和 `main`,其中 `fmt` 用於格式化輸入和輸出,`main` 用於生成可執行程式碼。
步驟 2 − 建立一個 `main` 函式。
步驟 3 − 在 `main` 函式中,使用 `make` 函式(Go 語言內建函式)建立一個雜湊對映。
步驟 4 − 將值賦給對映中的鍵。
步驟 5 − 在此步驟中,設定要獲取其值的鍵。
步驟 6 − 然後,使用 `found` 變數檢視該值是否存在於對映中。
步驟 7 − 如果 `found` 為真,則列印鍵的值。
步驟 8 − 如果 `found` 為假,則表示未為該鍵獲取任何值。
步驟 9 − 使用 `fmt` 包中的 `Printf` 函式執行列印語句。
示例 1
在此示例中,我們將使用內建函式 `make` 函式建立一個雜湊對映。然後,使用 `found` 變數獲取指定鍵的值。
package main
import "fmt"
func main() {
hashmap := make(map[string]string)
hashmap["saree"] = "red"
hashmap["kurti"] = "blue"
hashmap["jacket"] = "green"
key := "saree"
value, found := hashmap[key]
if found {
fmt.Printf("The value for key '%s' is '%s'\n", key, value)
} else {
fmt.Printf("No value found for key '%s'\n", key)
}
}
輸出
The value for key 'saree' is 'red'
示例 2
在此示例中,我們將建立一個雜湊對映,並使用 `ok` 判斷法根據鍵查詢對映中的值。`ok` 返回真或假。
package main
import "fmt"
func main() {
hashmap := map[string]int{
"pencils": 5,
"pens": 10,
"registers": 15,
}
key := "pens"
value, ok := hashmap[key]
if ok {
fmt.Printf("The value for key '%s' is '%d'\n", key, value)
} else {
fmt.Printf("No value found for key '%s'\n", key)
}
}
輸出
The value for key 'pens' is '10'
結論
我們已成功編譯並執行了該程式,以根據指定鍵獲取值。在第一個示例中,我們使用 `found` 變數根據指定鍵獲取值;在第二個示例中,我們使用 `ok` 判斷法執行操作。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP