This is a creation in Article, where the information may have evolved or changed. Welcome to the 13th Tutorial [Golang Series Tutorial] (/SUBJECT/2). # # What is a map? Map is the built-in type associated with the value in Go and the key (key). The value can be obtained by the corresponding key. # # How do I create a map? You can create a map by passing in the type of key and value to the ' Make ' function. ' Make (Map[type of Key]type of Value) ' is the syntax for creating a map. The code above "Gopersonsalary: = Make (Map[string]int)" creates a map named ' Personsalary ' where the key is of type string and the value is int. The 0 value of map is ' nil '. If you want to add elements to the nil map, the run-time panic will be triggered. Therefore, the map must be initialized with the ' Make ' function. "' Gopackage mainimport (" FMT ") func main () {var personsalary map[string]intif personsalary = nil {fmt. PRINTLN ("Map is nil. Going to make one. ") Personsalary = Make (Map[string]int)}} "[Online Run Program] (Https://play.golang.org/p/IwJnXMGc1M) above the program, Personsalary is nil, So you need to initialize with the Make method, and the program will output ' map is nil '. Going to make one. # # Add elements to map the syntax and arrays for adding new elements to the map are the same. The following program adds several new elements to the ' personsalary ' map. "' Gopackage mainimport (" FMT ") func main () {personsalary: = Make (Map[string]int) personsalary[" Steve "] = 12000personsalary["Jamie" = 15000personsalary["Mike"] = 9000fmt. PRINTLN ("Personsalary Map contents:", Personsalary)}"[Running Program Online] (HTTPS://PLAY.GOLANG.ORG/P/V1LNQ4IGW1) above the program output: ' Personsalary map contents:map[steve:12000 jamie:15000 MIKE:9000] ' You can also initialize the map at the time of declaration. "' Gopackage mainimport (" FMT ") func main () {personsalary: = map[string]int {" Steve ": 12000," Jamie ": 15000,}personsalary ["Mike"] = 9000fmt. PRINTLN ("Personsalary Map contents:", Personsalary)} "[Online Run Program] (https://play.golang.org/p/nlH_ADhO9f) the above program declares Personsalary, and adds two elements at the same time as the declaration. And then added the key ' Mike '. Program output: ' personsalary map contents:map[steve:12000 jamie:15000 mike:9000] ' key is not necessarily a string type. All comparable types, such as boolean,interger,float,complex,string, can be used as keys. For comparable types, visit [http://golang.org/ref/spec#Comparison_operators] (http://golang.org/ref/spec#Comparison_operators) If you want to learn more. # # to get the elements in a map now we've added several elements to map, so we're going to learn how to get them. The syntax for getting the map element is ' Map[key '. "' Gopackage mainimport (" FMT ") func main () {personsalary: = map[string]int{" Steve ": 12000," Jamie ": 15000,}personsalary ["Mike"] = 9000employee: = "Jamie" FMT. Println ("Salary of", Employee, "is", Personsalary[employee])} "[Online Running program] (HTTPS://PLAY.GOLANG.ORG/P/-TSBAC7F1V) The above program is very simple. Get and print employee ' Jamie ' salary. Program output ' Salary of Jamie is 15000 '. What happens if we get an element that doesn't exist? Map returns a value of 0 for that element type. In the ' personsalary ' map, if we get a nonexistent element, we return an ' int ' type of 0 value ' 0 '. "' Gopackage mainimport (" FMT ") func main () {personsalary: = map[string]int{" Steve ": 12000," Jamie ": 15000,}personsalary ["Mike"] = 9000employee: = "Jamie" FMT. Println ("Salary of", Employee, "is", Personsalary[employee]) fmt. Println ("Salary of Joe is", personsalary["Joe"])} "[Running Program Online] (https://play.golang.org/p/EhUJhIkYJU) above program output:" ' Salary Of Jamie is 15000Salary of the Joe is 0 "' above the program returns ' Joe ' salary is 0. We will not get any run-time errors when ' Joe ' is not included in ' Personsalary '. If we want to know if there is a "key" in the map, what to do: "' govalue, OK: = Map[key]" is the syntax for getting a key in the map. If ' OK ' is true, indicating that the key exists, the value corresponding to key is ' value ', and vice versa means that key does not exist. "' Gopackage mainimport (" FMT ") func main () {personsalary: = map[string]int{" Steve ": 12000," Jamie ": 15000,}personsalary ["Mike"] = 9000newEmp: = "Joe" value, OK: = personsalary[newemp]if OK = = true {fmt. Println ("SAlary of ", Newemp," is ", value)} else {fmt. Println (Newemp, "Not Found")}} "[Online Run Program] (https://play.golang.org/p/q8fL6MeVZs) above the program, line 15th, ' Joe ' does not exist, so ' OK ' is false. The program will output: ' Joe not found ' iterates through all the elements in the map and needs a ' for range ' loop. "' Gopackage mainimport (" FMT ") func main () {personsalary: = map[string]int{" Steve ": 12000," Jamie ": 15000,}personsalary ["Mike"] = 9000fmt. Println ("All items of a map") for key, value: = Range Personsalary {fmt. Printf ("personsalary[%s] =%d\n", key, Value)}} "[Running Program Online] (https://play.golang.org/p/gq9ZOKsI9b) above program output: ' ' All items ' of a mappersonsalary[mike] = 9000personsalary[steve] = 12000personsalary[jamie] = 15000 "__ is a bit important when using ' for range ' to traverse the map , it is not guaranteed that the order of elements obtained by the executing program is the same. __## Delete the elements in the map remove the syntax for ' key ' in ' map ' [_delete (Map, key) _] (https://golang.org/pkg/builtin/#delete). This function has no return value. "' Gopackage mainimport (" FMT ") func main () {personsalary: = map[string]int{" Steve ": 12000," Jamie ": 15000,}personsalary ["Mike"] = 9000fmt. PRINTLN ("Map before deletion", personsalary) Delete (Personsalary, "Steve ") Fmt. PRINTLN ("Map after deletion", personsalary)} "[Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/NROJZEF-A7) The above program removed the key" Steve ", Output: ' "Map before deletion map[steve:12000 jamie:15000 mike:9000]map after deletion map[mike:9000 jamie:15000]" ' # # Get the length of the map obtained Take the length of the map using the [Len] (https://golang.org/pkg/builtin/#len) function. "' Gopackage mainimport (" FMT ") func main () {personsalary: = map[string]int{" Steve ": 12000," Jamie ": 15000,}personsalary ["Mike"] = 9000fmt. Println ("Length is", Len (personsalary))} "[Online Run Program] (Https://play.golang.org/p/8O1WnKUuDP) _len in the above program (personsalary ) _ function Gets the length of the map. Program output ' length is 3 '. # # Map is a reference type similar to [slices] (https://golangbot.com/arrays-and-slices/), and map is also a reference type. When a map is assigned a new variable, they point to the same internal data structure. Therefore, changing one of the variables will affect the other variable. "' Gopackage mainimport (" FMT ") func main () {personsalary: = map[string]int{" Steve ": 12000," Jamie ": 15000,}personsalary ["Mike"] = 9000fmt. Println ("Original person salary", personsalary) Newpersonsalary: = personsalarynewpersonsalary["Mike"] = 18000fmt. Println ("Person salary CHAnged ", Personsalary)} ' [Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/OGFL3ADDQ1) above the 14th line of the program, ' Personsalary ' is assigned to ' Newpersonsalary '. On the next line, ' Mike ' in ' Newpersonsalary ' has become ' 18000 '. The ' Mike ' salary in ' personsalary ' will also become ' 18000 '. Program output: ' ' Original person salary map[steve:12000 jamie:15000 Mike:9000]person salary changed map[steve:12000 jamie:15000 MIKE:18000] "The same happens when map is passed as a function parameter. Any modifications to the map in the function are visible to external calls. # # Map Equality map cannot be judged by the ' = = ' operator, ' = = ' can only be used to check if the map is ' nil '. "' Gopackage MainFunc Main () {map1: = map[string]int{" One ": 1," one ": 2,}map2: = map1if Map1 = map2 {}}" [Run Program Online] (https:/ /PLAY.GOLANG.ORG/P/MALQDYWKCT) above program throws compilation error **invalid Operation:map1 = = MAP2 (map can only is compared to nil) * *. The way to determine whether two maps are equal is to traverse each element in the comparison of two maps. I suggest you write a program like this to implement this function:). I have implemented all the concepts we have discussed in a program. You can download the code from [GitHub] (https://github.com/golangbot/maps). This is map. Thank you for reading. Good * * Previous tutorial-[Variadic Function] (https://studygolang.com/articles/12173) * * * Next tutorial-[string] (https://studygolang.com/articles/12261) * *
via:https://golangbot.com/maps/
Author: Nick Coghlan Translator: arisaries proofreading: Noluye
This article by GCTT original compilation, go language Chinese network honor launches
This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove
3,170 Reads