Go datatype map

Foreword

 Go language provides a mapping between container map, its internal 散列表(hash)implementation. Similar dictionary in Python.

 

The basic operation and define a map

package main

import "fmt"

func main() {
	// define a map variable, key is sring type, value is of type int
	var m1 map[string]int
	fmt.Println (m1 == nil) // not initialized (no open space in memory)
	// Initialization: a good map of the estimated capacity expansion during the run to avoid
	m1 = make(map[string]int, 10)
	m1 [ "Age"] = 18
	fmt.Println(m1)
	fmt.Println (m1 [ "Age"])
	// Get the key does not exist
	v, ok := m1["姓名"]
	if !ok {
		fmt.Println ( "not the key")
	} else {
		fmt.Println (v)
	}
	// direct access key does not exist, and returns the default value of the corresponding type
	fmt.Println (m1 [ "does not exist in the key"])

	// traverse the map of the key and value
	m2 := make(map[string]string, 10)
	m2["姓名"] = "Martin"
	m2 [ "sex"] = "male"
	for k, v := range m2 {
		fmt.Println (k, v)
	}
	// traverse only map the keys
	for k := range m2 {
		fmt.Println (k)
	}
	// traverse the only map of values
	for _, v := range m2 {
		fmt.Println (v)
	}
	// delete the key map
	delete (m2, "name")
	fmt.Println(m2)
	// delete the map does not exist in the key () no-option
	delete (m1, "the absence of key")
	/*
	go doc builtin.delete view the built-in functions usage
	func delete(m map[Type]Type1, key Type)
    The delete built-in function deletes the element with the specified key
    (m[key]) from the map. If m is nil or there is no such element, delete is a
    Now-on.
	*/

}

  

Guess you like

Origin www.cnblogs.com/sss4/p/12590944.html