Golang Data type Map

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

1 Map Introduction

Map is a bunch of unordered sets of key-value pairs, similar to the concept of a dictionary in Python, which is formatted as Map[keytype]valuetype and is a key-value hash structure. Map reads and sets are similar to slice, with key to operate, only the slice index can only be an int type, and map many more types, can be int, can be a string and all the types that fully define the = = and! = operations.
In C++/java, maps are generally provided as libraries, such as STL's STD::MAP<> in C + +, which is hashmap<> in Java and, in these languages, if you want to use a map, refer to the appropriate library beforehand. In go, using map does not need to introduce any libraries, and it is more convenient to use them.

2 Map Declaration

The syntax for declaring a map is as follows

var map variable name Map[key] Value
Where: Key is key type, value is type

For example: value can be not only a callout data type, but also a custom data type

var numbers map[string] Intvar myMap map[string] PersonInfo

Personinfo is a custom structure that stores personal information, defined as follows

Type personInfo struct {    ID string    Name string    Address string}

3 Map Initialization

3.1 Direct initialization (creation)

Rating: = map[string] float32 {"C": 5, "Go": 4.5, "Python": 4.5, "C + +": 2}mymap: = map[string] personinfo{"1234": personinfo{ "1", "Jack", "101,..."},}

3.2 Initialize with make (create)

The built-in function make () provided by the go language can be used to create a map with flexibility.

Created a map with a key type of string and a value of type int
Numbers: = make (map[string] int)
Created a map with a key type of string and a value type of Personinfo
MyMap = Make (map[string] personInfo)
You can also choose whether to specify the initial storage capacity of the map at creation time, such as creating a map with an initial storage capacity of 5
MyMap = Make (Map[string] personInfo, 5)

After creation, initialize as follows:

numbers["one"] = 1 mymap["1234"] = personinfo{"1", "Jack", "Hostel 101,..."}

4 Map Element Lookup

In the Go language, map lookup functions are designed to be more sophisticated. To determine if a particular key was found successfully, you do not need to check to see if the value is nil, just look at the second return value. To find a specific key from the map, you can do so by using the following code:

Value, OK: = mymap["1234"]if ok{    //process found value}
5 Map element Modification (Assignment)

5.1 Direct Modification

numbers["one"] = 11

5.2 Indirect Modification

Map is a reference type, and if two maps point to one level at a time, then one changes and the other changes accordingly.

Numberstest: = numbersnumberstest["one"] = "111"
now the value of numbers["one" has changed to "111".

6 Map Element Deletion

The go language provides a built-in function delete () to delete elements within a container. Such as

Delete (number, "one")

The above code removes key-value pairs with the key "one" from the Mymap. If the "one" key does not exist, then this call will not happen, and there will be no side effects. However, if the value of the incoming map variable is nil, the call causes the program to throw an exception (panic).

7 Instance Code

Package Mainimport ("FMT") type Persioninfo struct{ID string Name string Address string}func main () {/* Declares a map variable numbers, the key name is string, the value is int var numbers map[string] Int//Creates a value for the map variable, and specifies a maximum of 3 int values numbers = make (map[st Ring] int, 3)//map element assignment numbers["one"] = 1 numbers["one"] = 2 numbers["three"] = 3 */////////////The shorthand method for the above methods num Bers: = map[string] int{"One": 1, "one": 2, "three": 3,} var myMap map[string] Persioninf o MyMap = Make (map[string] persioninfo) mymap["persion1"] = persioninfo{"1", "Amiee", "Street 101"} mymap["Persio    N2 "] = persioninfo{" 2 "," Beva "," Street 102 "} mymap[" Persion3 "] = persioninfo{" 3 "," Cencey "," Street 103 "}/* Shorthand method for the above methods myMap: = Map[string] persioninfo{"persion1": persioninfo{"1", "Amiee", "Street 101"}, "per        Sion2 ": persioninfo{" 2 "," Beva "," Street 102 "}," Persion3 ": persioninfo{" 3 "," Cencey "," Street 103 "},} */ The map element prints the FMT. Printf ("%v\n", numbers) fmt. PRINTLN (Numbers) fmt. Println (numbers[","]) fmt. Println (MYMAP) fmt. Println (mymap["Persion1"])//map element find P1, OK: = mymap["Persion1"] if ok{fmt. Println ("Found persion1, Name", p1. Name, ", info", p1)}else{fmt.    Println ("Not Found Persion1")}//map Element Modification//map is a reference type, and if two maps point to one level at a time, then one change and the other changes accordingly. Numberstest: = Numbers numberstest["one"] = one FMT. PRINTLN (Numbers)//map element deletes delete (numbers, "one") fmt. PRINTLN (Numbers)}

The output is as follows

[Root@localhost mygo]# go run  test.go map[one:1 two:2 three:3]map[one:1 two:2 three:3]2map[persion1:{1 Amiee Street 1 Persion2:{2 Beva Street 102} persion3:{3 Cencey Street 103}]{1 Amiee Street 101}found persion1, name Amiee, info {1 A Miee Street 101}map[one:11 two:2 three:3]map[two:2 Three:3]

8 Precautions

Map is unordered, each time the map will be different, it can not be obtained through the index, but must be obtained through key.
The length of the map is not fixed, that is, like slice, is also a reference type.
The built-in Len function also applies to the map, returning the number of keys the map has.
The value of the map can be easily modified by re-assigning the value.


< keywords: map make delete >

**********************************************************************************************
  Reprint Please specify source: http://blog.csdn.net/jesseyoung/article/details/34949845
******************************************

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.