Golang 将项目存储到哈希集合
在Golang中,哈希表是哈希集合的一部分,它以键值对的形式存储值。在本文中,我们将使用两个不同的示例将项目存储在哈希集合中。在第一个示例中,将使用索引将项目存储在映射中,在第二个示例中将使用项目结构来存储项目。
语法
func make ([] type, size, capacity)
go语言中的make函数用于创建数组/映射,它接受要创建的变量类型、大小和容量作为参数。
步骤
- 在程序中创建一个名为main的包并声明fmt(格式化包),其中main用于产生可执行代码,fmt用于格式化输入和输出。
-
使用map字面量和make函数创建一个哈希映射,其中键的类型为字符串,值的类型为整数。
-
使用索引将值添加到哈希映射中,例如pencil=10,pen=20和scale=15。
-
值添加完成后,在控制台上打印哈希映射。
-
在此步骤中,通过索引访问键的值来操作哈希映射。
-
然后,再次使用索引更新键的值。
-
然后,使用delete函数从映射中删除特定键,并在控制台上打印更新后的映射。
-
使用从fmt包的Println()函数执行打印语句,其中的ln表示新行。
示例1
在这个示例中,我们将使用内置的make函数创建一个哈希映射,然后使用索引添加所需的值到映射中。这里,我们将使用三个值,然后使用fmt包将它们打印在终端上,并使用不同的操作对哈希映射进行操作。让我们来看一下代码和算法,以了解它的实际工作方式。
package main
import "fmt"
func main() {
// Initialize an empty map with string keys and integer values
hashmap := make(map[string]int)
// Add some items to the map
hashmap["pencil"] = 10
hashmap["pen"] = 20
hashmap["scale"] = 15
// Print the entire map
fmt.Println("The hashmap created above is: ")
fmt.Println(hashmap)
// Access a specific item by its key
fmt.Println("The value of specific element from hashmap is:")
fmt.Println(hashmap["pencil"])
// Update the value of an existing item
hashmap["scale"] = 20
// Delete an item from the map
delete(hashmap, "pencil")
// Print the updated map
fmt.Println("The hashmap after deleting an item from it is:")
fmt.Println(hashmap)
}
输出
The hashmap created above is:
map[pen:20 pencil:10 scale:15]
The value of specific element from hashmap is:
10
The hashmap after deleting an item from it is:
map[pen:20 scale:20]
示例2
在这个示例中,我们将创建一个哈希映射,就像上一个示例中做的那样,但是这里我们还将创建一个item结构的实例来创建键值对,然后将这些项添加到哈希映射中并操作哈希映射。输出将使用fmt包进行打印。让我们看一下代码和算法。
package main
import "fmt"
// Define a struct to represent an item
type Item struct {
Name string
Quantity int
}
func main() {
// Initialize an empty map with string keys and Item values
hashmap := make(map[string]Item)
// Create item instances and add them to hashmap
pen := Item{Name: "pen", Quantity: 10}
pencil := Item{Name: "pencil", Quantity: 20}
registers := Item{Name: "registers", Quantity: 30}
hashmap[pen.Name] = pen
hashmap[pencil.Name] = pencil
hashmap[registers.Name] = registers
// Print the entire map
fmt.Println("The entire map is presented as follows: ")
fmt.Println(hashmap)
// Access a specific item by its key
fmt.Println("The value of the element is accessed as follows:")
fmt.Println(hashmap["pencil"])
// Update the value of an existing item
pen.Quantity = 50
hashmap[pen.Name] = pen
// Delete an item from the map
delete(hashmap, pencil.Name)
// Print the updated map
fmt.Println("The updated map after deleting the data item is:")
fmt.Println(hashmap)
}
输出
The entire map is presented as follows:
map[pen:{pen 10} pencil:{pencil 20} registers:{registers 30}]
The value of the element is accessed as follows:
{pencil 20}
The updated map after deleting the data item is:
map[pen:{pen 50} registers:{registers 30}]
结论
我们执行了将项目存储到哈希集合中的程序,使用了两个示例。在第一个示例中,我们使用索引来存储项目,在第二个示例中,我们使用结构体来存储项目。