In golang, map is a special data structure. It is an unordered collection in the form of key (index) and value (value). It can also be called an associative array or dictionary; map is a The ideal structure that can quickly find values is a data structure that can quickly find the corresponding value based on a given key.
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
Map in Go language is a special data structure, an unordered collection of element pairs (pair). Pair corresponds to a key (index) and a value (value), so this structure is also called Associative array or dictionary is an ideal structure that can quickly find values. Given a key, the corresponding value can be quickly found.
The key of Golang's map can be any data type that can be compared using ==, such as int, string, bool, etc., and the value can be any type.
Map is an unordered data structure, so the same map may be obtained in an inconsistent order each time it is traversed.
map concept
map is a reference type and can be declared in the following way:
var mapname map[keytype]valuetype
where:
mapname is the variable name of map.
keytype is the key type.
valuetype is the value type corresponding to the key.
Tip: Spaces are allowed between [keytype] and valuetype.
You do not need to know the length of the map when declaring it, because the map can grow dynamically. The value of an uninitialized map is nil. You can use the function len() to get the number of pairs in the map.
[Example]
package main import "fmt" func main() { var mapLit map[string]int //var mapCreated map[string]float32 var mapAssigned map[string]int mapLit = map[string]int{"one": 1, "two": 2} mapCreated := make(map[string]float32) mapAssigned = mapLit mapCreated["key1"] = 4.5 mapCreated["key2"] = 3.14159 mapAssigned["two"] = 3 fmt.Printf("Map literal at \"one\" is: %d\n", mapLit["one"]) fmt.Printf("Map created at \"key2\" is: %f\n", mapCreated["key2"]) fmt.Printf("Map assigned at \"two\" is: %d\n", mapLit["two"]) fmt.Printf("Map literal at \"ten\" is: %d\n", mapLit["ten"]) }
Output result:
In the example, mapLit demonstrates the use of {key1: value1, key2: value2} format to initialize maps, just like arrays and structures.
The creation method of mapCreated in the above codemapCreated := make(map[string]float)
is equivalent to mapCreated := map[string]float{}
.
mapAssigned is a reference to mapList, and modifications to mapAssigned will also affect the value of mapLit.
Note: You can use make(), but you cannot use new() to construct a map. If you use new() incorrectly to allocate a reference object, you will get a null reference pointer, which is equivalent to declaring a Uninitialized variable and took its address:
mapCreated := new(map[string]float)
Next, when we call mapCreated["key1"] = 4.5, the compiler will report an error:
invalid operation: mapCreated["key1"] (index of type *map[string]float).
map capacity
Different from arrays, map can dynamically expand and contract according to the new key-value, so it does not have a fixed length or maximum limit, but you can also choose to mark the map Initial capacity capacity, the format is as follows:
make(map[keytype]valuetype, cap)
For example:
map2 := make(map[string]float, 100)
When the map grows to the upper capacity limit, if a new key-value is added, the size of the map will automatically increase by 1, so For performance reasons, for large maps or maps that will expand rapidly, even if the capacity is only roughly known, it is best to indicate it first.
Here is a specific example of map, that is, mapping musical scales to corresponding audio:
noteFrequency := map[string]float32 { "C0": 16.35, "D0": 18.35, "E0": 20.60, "F0": 21.83, "G0": 24.50, "A0": 27.50, "B0": 30.87, "A4": 440}
[Related recommendations: Go video tutorial, programming teaching】
The above is the detailed content of What is map in golang. For more information, please follow other related articles on the PHP Chinese website!

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

ThebytespackageinGoiscrucialforhandlingbyteslicesandbuffers,offeringtoolsforefficientmemorymanagementanddatamanipulation.1)Itprovidesfunctionalitieslikecreatingbuffers,comparingslices,andsearching/replacingwithinslices.2)Forlargedatasets,usingbytes.N

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools
