Go语言实现常见数据结构-5. 散列表(HashMap)

package main

import "fmt"

// HashMap structure using a map
type HashMap struct {
	items map[string]int
}

// Initialize a new hash map
func (h *HashMap) Init() {
	h.items = make(map[string]int)
}

// Insert a key-value pair into the hash map
func (h *HashMap) Insert(key string, value int) {
	h.items[key] = value
}

// Get a value by key from the hash map
func (h *HashMap) Get(key string) int {
	if value, found := h.items[key]; found {
		return value
	}
	return -1 // Key not found
}

// Delete a key-value pair from the hash map
func (h *HashMap) Delete(key string) {
	delete(h.items, key)
}

func main() {
	hashMap := HashMap{}
	hashMap.Init()
	hashMap.Insert("a", 1)
	hashMap.Insert("b", 2)
	fmt.Println(hashMap.Get("a")) // 1
	fmt.Println(hashMap.Get("b")) // 2
	hashMap.Delete("a")
	fmt.Println(hashMap.Get("a")) // -1
}

上一篇:windows11下vscode配置lua环境