SoFunction
Updated on 2025-03-05

The basic operation and definition method of golang map

Basic operation of map

How to define map

Since map is a reference type, it must be initialized when operating

Method 1:

var a map[string]int
	a = make(map[string]int, 16)
	("a = %#v \n", a)
	a["stu01"] = 1000

Method 2:

a := map[string]int{
		"stu01": 100,
		"stu03": 300,
		"stu02": 200,
	}
	("a = %#v \n", a)

Determine whether the key exists

When obtaining the value of the map, you can receive two values, one is the obtained value, and the other is to determine whether the bool type exists. If it exists, return the corresponding value. Bool is true, does not exist, return the empty value of the corresponding type, and bool is false

func test3() {
	var a map[string]int
	a = make(map[string]int, 16)
	("a = %#v \n", a)
	a["stu01"] = 1000
	a["stu02"] = 2000
	var result int
	var ok bool
	var key string = "stu04"
	result, ok = a[key]
	if ok == false {
		("key is %s is not exist\n", key)
	} else {
		("key is %s = %d \n", key, result)
	}
}

traversal key, value of map

Use the for ... range method to traverse and get the values ​​in it

func test4() {
	(().UnixNano())

	var a map[string]int
	a = make(map[string]int, 1024)
	for i := 0; i < 128; i++ {
		key := ("stu%d", i)
		value := (1000)
		a[key] = value
	}
	for key, value := range a {
		("map[%s]=%d\n", key, value)
	}
}

map delete element

Use the built-in delete method to delete

func test5() {
	var a map[string]int
	a = make(map[string]int, 16)
	("a = %#v \n", a)
	a["stu01"] = 1000
	a["stu02"] = 2000
	a["stu03"] = 3000
	("a = %#v \n", a)
	delete(a, "stu02")
	("DEL after a = %#v \n", a)
}

Delete all of them, need to use a for loop, delete them one by one

The length of the map

Use len built-in function to find out

Copying map

map is a reference type. In the system, when copying, the memory address pointed to is the same, so if you modify one, the others will also be changed accordingly.

func test6() {
	var a map[string]int
	if a == nil {
		a = make(map[string]int, 16)
		a["stu01"] = 1000
		a["stu02"] = 2000
		a["stu03"] = 3000
		("a = %#v \n", a)
		b := a
		b["stu01"] = 8888
		("after modify a : %#v\n", a)
	}
}

Slice of map

Since the value of map can be an array or an int, when the value is an array, it also needs to be initialized first when using it

func main() {
	(().UnixNano())
	var s []map[string]int
	s = make([]map[string]int, 5, 16)
	for index, value := range s {
		("slice[%d] = %v \n", index, value)
	}
	()
	s[0] = make(map[string]int, 16)
	s[0]["stu01"] = 1000
	s[0]["stu02"] = 2000
	s[0]["stu03"] = 3000
	for index, value := range s {
		("slice[%d] = %v \n", index, value)
	}
}

This is the end of this article about the basic operations of golang-map. For more related golang map content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!