How to use new to construct Map in go language

Prerequisite reading:

Don't use new, always use make to construct map

Note that if you mistakenly allocate a reference object using new (), you will get a null reference pointer, which is equivalent to declaring an uninitialized variable and taking its address:

mapCreated := new(map[string]float32) Next, when we call: mapCreated["key1"] =
4.5, the compiler will report an error:

invalid operation: mapCreated[“key1”] (index of type
*map[string]float32).

To summarize the reasons why not use new:

The new function can create an empty map, but this map is an empty map pointer. Therefore, this map needs to be initialized before using it.

How to create a Map using new

It is possible to create a map using the new function, but this requires explicitly assigning a pointer to a map variable and manually initializing the map. Here is an example of using the new function to create and initialize a map:

mapCreated := new(map[string]float32)
*mapCreated = make(map[string]float32)
(*mapCreated)["key1"] = 4.5

It should be noted that mapCreated in the above code is a pointer to map[string]float32 type, so the * operator needs to be used to access the actual map value pointed by the pointer. In addition, we also need to manually use the make function to initialize the map after using the new function. Finally, we can assign to the map by dereferencing the pointer and using key-value syntax.

In short, it is possible to create a map using the new function, but it requires manual initialization and assignment operations, which is more troublesome. Therefore, it is recommended to use the make function directly to create and initialize the map, which is more convenient and intuitive.

Guess you like

Origin blog.csdn.net/qq_46110497/article/details/129630857