Home > Backend Development > Golang > How to create map in golang

How to create map in golang

Release: 2019-12-25 10:31:30
Original
5410 people have browsed it

How to create map in golang

map is an unsorted collection of key-value pairs, similar to the concept of a dictionary in Python. Its format is map[keyType]valueType, which is a key-value hash structure. The reading and setting of map are also similar to slice, and are operated through key, except that the index of slice can only be int type, while map has many more types, including int, string and all fully defined == and != The type of operation.

The syntax for declaring a map is as follows:

var map变量名 map[key] value
Copy after login

Among them: key is the key type, value is the value type

For example: value can not only be annotation data type, but also self- Define the data type

var numbers map[string] int
var myMap map[string] personInfo
Copy after login

personInfo as a custom structure to store personal information, defined as follows

type personInfo struct {
   ID string 
   Name string 
   Address string
}
Copy after login

map initialization:

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", "Room 101,..."},}
Copy after login

2. Initialization (creation) through make

The built-in function make() provided by the Go language can be used to flexibly create maps.

Created a map with key type string and value type int

numbers := make(map[string] int)
Copy after login

Created a map with key type string and value type personInfo

myMap = make(map[string] personInfo)
Copy after login

can also be used Choose whether to specify the initial storage capacity of the map when creating it. For example, create a map with an initial storage capacity of 5

myMap = make(map[string] personInfo, 5)
Copy after login

After creation, the initialization is as follows:

numbers["one"] = 1 
myMap["1234"] = personInfo{"1", "Jack", "Room 101,..."}
Copy after login

For more golang knowledge, please pay attentiongolang tutorial column.

The above is the detailed content of How to create map in golang. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
How to choose golang web mvc framework
From 1970-01-01 08:00:00
0
0
0
Is it necessary to use nginx when using golang?
From 1970-01-01 08:00:00
0
0
0
golang - vim plug-in to write go
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template