当前位置:网站首页>[golang] quick review guide quickreview (III) - Map

[golang] quick review guide quickreview (III) - Map

2022-06-23 20:22:00 DDGarfield

A scientific name : Mapping relation container .

Common name : Key value pair key-value

map Follow slice equally , It is still a reference type .

map

1.C# Dictionary in

according to map Characteristics , The blogger's analogy is C# Chinese Dictionary Dictionary, Are also key value pairs .

// Definition   initialization 
Dictionary<int, string> dic = new Dictionary<int, string>
{
    {1," Student "},
    {2," teacher "},
    {3," Parent "}
};

// newly added 
dic.Add(4, " The headmaster ");

// Judge whether it contains key
if (dic.ContainsKey(1))
{

}

// Judge whether it contains value
if (dic.ContainsValue(" Student ")) { }

// Ergodic dictionary 
foreach (KeyValuePair<int, string> kv in dic)
{

}
// Delete the specified key The elements of 
dic.Remove(1);

// Empty dictionary 
dic.Clear();

2.Golang Medium map

2.1 Definition initialization

make(map[KeyType]ValueType, [cap]),cap Optional

testMap := make(map[int]string, 3)
testMap[1] = " Student "
testMap[2] = " teacher "
testMap[3] = " Parent "
fmt.Println(testMap)
map[1: Student  2: teacher  3: Parent ]

2.2 Traverse

Use for k,v:=range map{} Traverse :

// Traverse 
for k, v := range testMap {
    fmt.Println(k, v)
}
1  Student 
2  teacher 
3  Parent 

2.3 Delete

Delete , Use built-in functions delete()

func delete(m map[Key]Type, key Key)
// Delete 
delete(testMap, 1)

for k, v := range testMap {
    fmt.Println(k, v)
}
3  Parent 
2  teacher 

2.4 The key is coming.

Slice is a type , And used frequently , Slicing can also be used as map Value value

var mapValueSlice = make(map[string][]string, 3)
var sc []string
sc = append(sc, " Chengdu ", " mianyang ", " Yibin ")
var sx = []string{" Xi'an ", " Hanzhong city ", " Yulin "}
mapValueSlice[" sichuan "] = sc
mapValueSlice[" shaanxi "] = sx
fmt.Println(mapValueSlice)
map[ sichuan :[ Chengdu   mianyang   Yibin ]  shaanxi :[ Xi'an   Hanzhong city   Yulin ]]

One last word ,golang To understand the source code, you need to have a solid basic syntax , The following function , Method recipient , The pointer , Parameters , Return value , Channels and so on , Look from a distance , brackets [] Flying across ,*, In fact, all changes can't be separated from their ancestors , These basic types are combined according to semantics .

Again : This series is not a tutorial , If you want to learn systematically , Bloggers can recommend learning resources .

原网站

版权声明
本文为[DDGarfield]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231850564512.html