HatchJS Logo

HatchJS.com

Cracking the Shell of Mystery

Golang: How to Assign a Value to an Entry in a Nil Map

Avatar

Golang Assignment to Entry in Nil Map

Maps are a powerful data structure in Golang, and they can be used to store key-value pairs. However, it’s important to be aware of the pitfalls of working with nil maps, as assigning a value to an entry in a nil map can cause unexpected results.

In this article, we’ll take a closer look at nil maps and how to avoid common mistakes when working with them. We’ll also discuss some of the best practices for using maps in Golang.

By the end of this article, you’ll have a solid understanding of nil maps and how to use them safely and effectively in your Golang programs.

| Column 1 | Column 2 | Column 3 | |—|—|—| | Key | Value | Error | | `nil` | `any` | `panic: assignment to entry in nil map` | | `map[string]string{}` | `”foo”: “bar”` | `nil` | | `map[string]string{“foo”: “bar”}` | `”foo”: “baz”` | `KeyError: key not found: foo` |

In Golang, a map is a data structure that stores key-value pairs. The keys are unique and can be of any type, while the values can be of any type that implements the `GoValue` interface. When a map is created, it is initialized with a zero value of `nil`. This means that the map does not exist and cannot be used to store any data.

What is a nil map in Golang?

A nil map is a map with a value of nil. This means that the map does not exist and cannot be used to store any data. When you try to access a nil map, you will get a `panic` error.

Why does Golang allow assignment to entry in a nil map?

Golang allows assignment to entry in a nil map because it is a type-safe language. This means that the compiler will check to make sure that the type of the value being assigned to the map entry is compatible with the type of the map. If the types are not compatible, the compiler will generate an error.

How to assign to entry in a nil map in Golang

To assign to an entry in a nil map, you can use the following syntax:

map[key] = value

For example, the following code will assign the value `”hello”` to the key `”world”` in a nil map:

m := make(map[string]string) m[“world”] = “hello”

Assignment to entry in a nil map is a dangerous operation that can lead to errors. It is important to be aware of the risks involved before using this feature.

Additional Resources

  • [Golang Maps](https://golang.org/ref/specMaps)
  • [Golang Type Safety](https://golang.org/ref/specTypes)

What is a nil map?

A nil map is a map that has not been initialized. This means that the map does not have any entries, and it cannot be used to store or retrieve data.

What are the potential problems with assigning to entry in a nil map?

There are two potential problems with assigning to entry in a nil map:

  • The first problem is that the assignment will silently fail. This means that the compiler will not generate an error, and the program will continue to run. However, the assignment will not have any effect, and the map will still be nil.
  • The second problem is that the assignment could cause a runtime error. This could happen if the program tries to access the value of the map entry. Since the map is nil, the access will cause a runtime error.

How to avoid problems with assigning to entry in a nil map?

There are two ways to avoid problems with assigning to entry in a nil map:

  • The first way is to check if the map is nil before assigning to it. This can be done using the `len()` function. If the length of the map is 0, then the map is nil.
  • The second way is to use the `make()` function to create a new map. This will ensure that the map is not nil.

Example of assigning to entry in a nil map

The following code shows an example of assigning to entry in a nil map:

package main

import “fmt”

func main() { // Create a nil map. m := make(map[string]int)

// Try to assign to an entry in the map. m[“key”] = 10

// Print the value of the map entry. fmt.Println(m[“key”]) }

This code will print the following output:

This is because the map is nil, and there is no entry for the key “key”.

Assigning to entry in a nil map can cause problems. To avoid these problems, you should always check if the map is nil before assigning to it. You can also use the `make()` function to create a new map.

Q: What happens when you assign a value to an entry in a nil map in Golang?

A: When you assign a value to an entry in a nil map in Golang, the map is created with the specified key and value. For example, the following code will create a map with the key “foo” and the value “bar”:

m := make(map[string]string) m[“foo”] = “bar”

Q: What is the difference between a nil map and an empty map in Golang?

A: A nil map is a map that has not been initialized, while an empty map is a map that has been initialized but does not contain any entries. In Golang, you can create a nil map by using the `make()` function with the `map` type and no arguments. For example, the following code creates a nil map:

m := make(map[string]string)

You can create an empty map by using the `make()` function with the `map` type and one argument, which specifies the number of buckets to use for the map. For example, the following code creates an empty map with 10 buckets:

m := make(map[string]string, 10)

Q: How can I check if a map is nil in Golang?

A: You can check if a map is nil in Golang by using the `nil` operator. For example, the following code checks if the map `m` is nil:

if m == nil { // The map is nil }

Q: How can I iterate over the entries in a nil map in Golang?

A: You cannot iterate over the entries in a nil map in Golang. If you try to iterate over a nil map, you will get a `panic` error.

Q: How can I avoid assigning a value to an entry in a nil map in Golang?

A: There are a few ways to avoid assigning a value to an entry in a nil map in Golang.

  • Use the `if` statement to check if the map is nil before assigning a value to it. For example, the following code uses the `if` statement to check if the map `m` is nil before assigning a value to it:

if m != nil { m[“foo”] = “bar” }

  • Use the `defer` statement to delete the entry from the map if it is nil. For example, the following code uses the `defer` statement to delete the entry from the map `m` if it is nil:

defer func() { if m != nil { delete(m, “foo”) } }()

m[“foo”] = “bar”

  • Use the `with` statement to create a new map with the specified key and value. For example, the following code uses the `with` statement to create a new map with the key “foo” and the value “bar”:

with(map[string]string{ “foo”: “bar”, })

In this article, we discussed the Golang assignment to entry in nil map error. We first explained what a nil map is and why it cannot be assigned to. Then, we provided several examples of code that would result in this error. Finally, we offered some tips on how to avoid this error in your own code.

We hope that this article has been helpful. If you have any other questions about Golang, please feel free to contact us.

Author Profile

Marcus Greenwood

Latest entries

  • December 26, 2023 Error Fixing User: Anonymous is not authorized to perform: execute-api:invoke on resource: How to fix this error
  • December 26, 2023 How To Guides Valid Intents Must Be Provided for the Client: Why It’s Important and How to Do It
  • December 26, 2023 Error Fixing How to Fix the The Root Filesystem Requires a Manual fsck Error
  • December 26, 2023 Troubleshooting How to Fix the `sed unterminated s` Command

Similar Posts

How to create a new dataframe from an existing dataframe in r.

Creating a new dataframe from an existing dataframe in R Dataframes are one of the most important data structures in R, and they’re used to store data in a tabular format. But what if you want to create a new dataframe from an existing dataframe? This is a common task, and there are a few…

How to Propagate Raspberry Cuttings: The Ultimate Guide

How to Propagate Raspberry Cuttings Raspberries are a delicious and versatile fruit that can be enjoyed fresh, frozen, or cooked into a variety of dishes. If you have a raspberry bush in your garden, you can easily propagate it by taking cuttings. This is a great way to grow more raspberries for yourself or to…

How to Become a Minecraft Marketplace Creator: A Guide for Developers

How to Become a Minecraft Marketplace Creator Minecraft is one of the most popular games in the world, with over 140 million active players. With so many people playing Minecraft, there’s a huge opportunity for creators to make money by selling their creations on the Minecraft Marketplace. In this article, we’ll walk you through the…

Trojan:Win32/Bearfoos.A.ml: What It Is and How to Remove It

Trojan:Win32/Bearfoos.A ML: What You Need to Know The Trojan:Win32/Bearfoos.A ML is a malicious software program that can infect your computer and steal your personal information. It is distributed through spam emails and fake websites, and once it is installed on your computer, it can: Monitor your online activity, including your browsing history, search queries, and…

How to Connect an Ice Maker Water Line to PEX Pipe

How to Connect an Ice Maker Water Line to PEX Do you have a new ice maker that you’re looking to install? Or maybe you’re just tired of your old ice maker and want to upgrade to a new one. Either way, you’ll need to connect the ice maker’s water line to your PEX plumbing….

Cypress: How to Wait for a Page to Fully Load

Cypress wait for page to fully load: A comprehensive guide When you’re testing a web page with Cypress, it’s important to make sure that the page is fully loaded before you start interacting with it. This is because if the page is still loading, you might not be interacting with the elements that you think…

Example error:

This panic occurs when you fail to initialize a map properly.

Initial Steps Overview

  • Check the declaration of the map

Detailed Steps

1) check the declaration of the map.

If necessary, use the error information to locate the map causing the issue, then find where this map is first declared, which may be as below:

The block of code above specifies the kind of map we want ( string: int ), but doesn’t actually create a map for us to use. This will cause a panic when we try to assign values to the map. Instead you should use the make keyword as outlined in Solution A . If you are trying to create a series of nested maps (a map similar to a JSON structure, for example), see Solution B .

Solutions List

A) use ‘make’ to initialize the map.

B) Nested maps

Solutions Detail

Instead, we can use make to initialize a map of the specified type. We’re then free to set and retrieve key:value pairs in the map as usual.

B) Nested Maps

If you are trying to use a map within another map, for example when building JSON-like data, things can become more complicated, but the same principles remain in that make is required to initialize a map.

For a more convenient way to work with this kind of nested structure see Further Step 1 . It may also be worth considering using Go structs or the Go JSON package .

Further Steps

  • Use composite literals to create map in-line

1) Use composite literals to create map in-line

Using a composite literal we can skip having to use the make keyword and reduce the required number of lines of code.

Further Information

https://yourbasic.org/golang/gotcha-assignment-entry-nil-map/ https://stackoverflow.com/questions/35379378/go-assignment-to-entry-in-nil-map https://stackoverflow.com/questions/27267900/runtime-error-assignment-to-entry-in-nil-map

The Go Blog

Go maps in action.

Andrew Gerrand 6 February 2013

Introduction

One of the most useful data structures in computer science is the hash table. Many hash table implementations exist with varying properties, but in general they offer fast lookups, adds, and deletes. Go provides a built-in map type that implements a hash table.

Declaration and initialization

A Go map type looks like this:

where KeyType may be any type that is comparable (more on this later), and ValueType may be any type at all, including another map!

This variable m is a map of string keys to int values:

Map types are reference types, like pointers or slices, and so the value of m above is nil ; it doesn’t point to an initialized map. A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic; don’t do that. To initialize a map, use the built in make function:

The make function allocates and initializes a hash map data structure and returns a map value that points to it. The specifics of that data structure are an implementation detail of the runtime and are not specified by the language itself. In this article we will focus on the use of maps, not their implementation.

Working with maps

Go provides a familiar syntax for working with maps. This statement sets the key "route" to the value 66 :

This statement retrieves the value stored under the key "route" and assigns it to a new variable i:

If the requested key doesn’t exist, we get the value type’s zero value . In this case the value type is int , so the zero value is 0 :

The built in len function returns on the number of items in a map:

The built in delete function removes an entry from the map:

The delete function doesn’t return anything, and will do nothing if the specified key doesn’t exist.

A two-value assignment tests for the existence of a key:

In this statement, the first value ( i ) is assigned the value stored under the key "route" . If that key doesn’t exist, i is the value type’s zero value ( 0 ). The second value ( ok ) is a bool that is true if the key exists in the map, and false if not.

To test for a key without retrieving the value, use an underscore in place of the first value:

To iterate over the contents of a map, use the range keyword:

To initialize a map with some data, use a map literal:

The same syntax may be used to initialize an empty map, which is functionally identical to using the make function:

Exploiting zero values

It can be convenient that a map retrieval yields a zero value when the key is not present.

For instance, a map of boolean values can be used as a set-like data structure (recall that the zero value for the boolean type is false). This example traverses a linked list of Nodes and prints their values. It uses a map of Node pointers to detect cycles in the list.

The expression visited[n] is true if n has been visited, or false if n is not present. There’s no need to use the two-value form to test for the presence of n in the map; the zero value default does it for us.

Another instance of helpful zero values is a map of slices. Appending to a nil slice just allocates a new slice, so it’s a one-liner to append a value to a map of slices; there’s no need to check if the key exists. In the following example, the slice people is populated with Person values. Each Person has a Name and a slice of Likes. The example creates a map to associate each like with a slice of people that like it.

To print a list of people who like cheese:

To print the number of people who like bacon:

Note that since both range and len treat a nil slice as a zero-length slice, these last two examples will work even if nobody likes cheese or bacon (however unlikely that may be).

As mentioned earlier, map keys may be of any type that is comparable. The language spec defines this precisely, but in short, comparable types are boolean, numeric, string, pointer, channel, and interface types, and structs or arrays that contain only those types. Notably absent from the list are slices, maps, and functions; these types cannot be compared using == , and may not be used as map keys.

It’s obvious that strings, ints, and other basic types should be available as map keys, but perhaps unexpected are struct keys. Struct can be used to key data by multiple dimensions. For example, this map of maps could be used to tally web page hits by country:

This is map of string to (map of string to int ). Each key of the outer map is the path to a web page with its own inner map. Each inner map key is a two-letter country code. This expression retrieves the number of times an Australian has loaded the documentation page:

Unfortunately, this approach becomes unwieldy when adding data, as for any given outer key you must check if the inner map exists, and create it if needed:

On the other hand, a design that uses a single map with a struct key does away with all that complexity:

When a Vietnamese person visits the home page, incrementing (and possibly creating) the appropriate counter is a one-liner:

And it’s similarly straightforward to see how many Swiss people have read the spec:

Concurrency

Maps are not safe for concurrent use : it’s not defined what happens when you read and write to them simultaneously. If you need to read from and write to a map from concurrently executing goroutines, the accesses must be mediated by some kind of synchronization mechanism. One common way to protect maps is with sync.RWMutex .

This statement declares a counter variable that is an anonymous struct containing a map and an embedded sync.RWMutex .

To read from the counter, take the read lock:

To write to the counter, take the write lock:

Iteration order

When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next. If you require a stable iteration order you must maintain a separate data structure that specifies that order. This example uses a separate sorted slice of keys to print a map[int]string in key order:

How to create object map of map(inside map )

Can any one tell me how to create inside map object…

Ex:- mapData := make(map[string]map[string]int) i try create object inside map but it thows error nil

That should make a nested map as you want it, but what do you mean by throwing error nil?

There is nothing thrown in golang and if you get an error == nil returned everything is fine, therefore I’ve some trouble to understand

Assigning to entries in a nil map will give you a panic. In your case you probably need to make() the nested maps when they don’t exist.

Sorry it s not thows if i assign value in neste map i get run time error assignment to entry in nil map , Create the object of nested map

my code is like this :- mapData := make(map[string]map[string]string) mapData[“golang”][“org”] = “google”

Okay Thank you

mapData := make(map[string]map[string]int)

inner, ok := mapData[“foo”] if !ok { inner = make(map[string]int) mapData[“foo”] = inner } inner[“bar”] = 42

If i add the new key value again it will create new nested map but i dont want to new object only one time i will create the nested map object then we can added value number of times, It is possible in go…please can you tell me

That is what the !ok check does.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.

Assignment to entry in nil map

golang nested map assignment to entry in nil map

Why does this program panic?

You have to initialize the map using the make function (or a map literal) before you can add any elements:

See Maps explained for more about maps.

Golang Programs

Golang Tutorial

Golang reference, beego framework, golang error assignment to entry in nil map.

Map types are reference types, like pointers or slices, and so the value of rect is nil ; it doesn't point to an initialized map. A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic; don't do that.

What do you think will be the output of the following program?

The Zero Value of an uninitialized map is nil. Both len and accessing the value of rect["height"] will work on nil map. len returns 0 and the key of "height" is not found in map and you will get back zero value for int which is 0. Similarly, idx will return 0 and key will return false.

You can also make a map and set its initial value with curly brackets {}.

Most Helpful This Week

Nested Maps in Go

I recently had to use a bunch of nested maps in Go and struggled way too long to get them “working”. And obviously there wasn’t a lot of good information to be found via $popular_search_engine. So i thought this might make a good blog post.

What gave me the proper nudge in the correct direction of thinking correctly was a Google Groups posting from 2012: https://groups.google.com/g/golang-nuts/c/PoRkoN84KKU/m/7330L9NulHQJ

You need to actually initialize every inner map seperatly if you want to use it! For more details you should read the rest ;-)

A simple example and the attempt of an explaination

Lets create a simple example to demonstrate the issue at hand:

Now open nested_maps.go in your favorite editor and paste in the following piece of code:

What we try to do here:

is to put a JSON array, where each array element contains three key-value pairs that define a group name, the persons name and their age, into a nested map. The intention for this might be that we think processing the data via a nested map is nice. Or whatever.

While this compiles perfectly fine, running the created binary will result in this runtime error:

My n00bish reaction at first was “WTF? I created the map with make() . It’s not nil!” But obviously i was terribly wrong.

What happens here is that Go creates the outer map but nothing else. And this makes perfect sense since it can’t possibly know how many inner maps we might want later on. It’s our job to take care of that.

A solution for that is extending our for loop like this:

The comments hopefully speak for themselves, but anyways: What we added is a simple check if the inner map to which we want write data already exists. This is done with a simple map lookup, which in Go returns not only the potential value but also a boolean value on which we can do a simple check with if . So if we get a false back, we just create the inner map with a make() and all is good.

Here is the full example which executes without a runtime error:

Hope this helps somebody else at some point in the future :-)

Golang Map – Syntax and Examples

Golang map stores the data values in key-value pairs. Go map is an unordered collection of key-value pairs where each key is unique and uses the key to access the element in a map.

Golang provides a built-in map type that implements a hash table and its type is reference types like slice or points in go.

In the Golang map default value is nil which is equivalent to an empty map.

The syntax to create a Go map is:

KeyType: any type

ValueType: any type including another map as well.

For example,

Where variable my_map is a map of string keys to int values.

Let’s create a map and try to add an element to the map.

The above example creates a map but doesn’t initialize it, so the value of my_map is nil . If you try to add an element to a nil map or empty map , it will result in a runtime panic error.

The output of the above program results in a panic runtime error.

Use the make function to create and initialize a map in golang. e.g.

In this tutorial, we will discuss golang map, how to create a map in golang, add elements to a map, and delete an element from the map.

How to Create a Map in Golang Using the make() function

To create a map in Golang, use the built-in make() function to create and initialize a map.

In the make function, provide the key type and value type, and it returns an initialized map.

In the above Golang program to create a map, we have used the make() function.

make() function creates and initializes a map hence you can add an element to it.

To add elements to the map, provide a value type value for each of the strings.e.g.

score[“Gary”] = 75 , create key-value pair where key = Gary and value = 75

Use the fmt.Println to print a map.

Use the len() function to get the total number of keys in a map. e.g. len(score)

How to Access the Values of a Map in Golang

Golang map stores the collection in key:value pairs.

To access the value of a map stored under the key, refer to the following code.

In the above golang map program, to retrieve the value of the key Gary , use score[“Gary”]

It returns the value 75 corresponding to the key Gary in a map.

Cool Tip: How to check if the key exists in a map in Go!

How to Delete Element from the Golang map

Use the delete() function to delete an element of the golang map.

In the above golang program to delete an element from the map using the key, it removes the element.

delete() function in go takes two arguments:

  • score – the name of the map
  • Mary – key of the element

Use Println() to print the updated map after deleting an element from the map and its length.

How to Iterate over Golang map

Golang map stores the unordered collection of elements in key-value pairs.

To access each of the elements in the Golang map, use the for range loop to iterate over the map.

The output of the above golang program to iterate over the map in go is:

In the above golang map program, to access each element of the map, use the for range loop .

I hope the above article on the golang map, how to create, access the map element, and delete elements from the map is helpful to you.

You can find more topics about the Golang tutorials on the  GolangSpot  Home page.

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

Get the Reddit app

Ask questions and post articles about the Go programming language and related tools, events etc.

An easier way to initialize the nested map?

And this code becomes bigger as we have more keys (deeper map).

So my questions is: Is there an easier way to initialize nested map or at least, is there a plugin for Jetbrains Goland which can build this code based on map keys.

By continuing, you agree to our User Agreement and acknowledge that you understand the Privacy Policy .

Enter the 6-digit code from your authenticator app

You’ve set up two-factor authentication for this account.

Enter a 6-digit backup code

Create your username and password.

Reddit is anonymous, so your username is what you’ll go by here. Choose wisely—because once you get a name, you can’t change it.

Reset your password

Enter your email address or username and we’ll send you a link to reset your password

Check your inbox

An email with a link to reset your password was sent to the email address associated with your account

Choose a Reddit account to continue

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Handling nil values in a map

I want to create a struct with the values in a map.

Here's a snippet:

The problem is, if one of the values is nil, panic occurs. So I wanted to do something like this:

But this is not a valid syntax.

Do I have to check every key separately to handle nil cases?

Élodie Petit's user avatar

  • 1>if the data type is know in advance then you must use a struct or map of structs 2> data,ok:=parts["facility"]; if ok && data!=nil {value=data.(int)} –  Nidhin David Commented Mar 7, 2021 at 17:02
  • golang.org/doc/faq#Does_Go_have_a_ternary_form –  Peter Commented Mar 7, 2021 at 17:30
  • See What is the idiomatic Go equivalent of C's ternary operator? –  icza Commented Mar 7, 2021 at 17:44

2 Answers 2

You can do this:

This will use the two-value form of type assertion, where the second value indicates if the type-assertion worked, and you then ignore that value, so the struct member is initialized with the zero-value if the map does not contain the key, or if the key is not of the required type.

Burak Serdar's user avatar

  • 1 Technically this is the 2-value form of the type assertion, not the map lookup. The nil interface value from the map is passed to the assertion which can then assert the interface to the desired zero value. –  JimB Commented Mar 7, 2021 at 20:47
  • @JimB, you are correct I fixed the answer –  Burak Serdar Commented Mar 7, 2021 at 21:01

You can write a wrapper for these types if you like:

which can be shortened if you want to use the default value for a type:

which will make it look like this:

You could go further and write your conversion functions locally:

gonutz's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged go or ask your own question .

  • Featured on Meta
  • Announcing a change to the data-dump process
  • We've made changes to our Terms of Service & Privacy Policy - July 2024

Hot Network Questions

  • In terms of Material Science, why do household garbage bag seal water and air, but allow odor to pass through?
  • In an expanding universe could black hole pairs keep orbiting each other forever?
  • Compact rotatable connection that supports pull forces?
  • How is the name "Took" pronounced?
  • How does the book get 34.71% percent as the answer?
  • Why is the E in 'collega' long?
  • Is math (only) a language?
  • Which programming language first used negative indexing to mean counting from the end?
  • How do you get on the list to be notified of realtime LSST alerts (like supernovae)?
  • Do strawberry seeds have different DNA within the same fruit?
  • What happens if your flight is cancelled on the last day of your visa; does it vary by country/region?
  • Efficient way to remove nailed-down plywood flooring in attic without damaging it?
  • Trimming direction on climb out and descent to maintain an airspeed
  • preventing replay attacks if it is done by radio signals
  • What is so fundamental about polynomial functions that they are used to demarcate the Hardness boundary in NP complexity classes?
  • Meaning of たり here
  • What is the color of the final disc(s)?
  • Can multi-threading improve performance of an IO-bound process?
  • What might be causing ls to ignore LS_COLORS for setgid (sg, g+s) directories?
  • What acceleration features did 2D PC video cards have? Comparing to video game consoles
  • Can conduit run be assembled, then wire pulled, and only then affixed to wall?
  • What is the difference of "limiting reactant" and "limiting reagent"?
  • Can an exponentially growing population perform eugenics and selective breeding at short time scales?
  • Cardinal arithmetic under determinacy

golang nested map assignment to entry in nil map

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

不要向nil map写入(panic: assignment to entry in nil map) #7

@kevinyan815

kevinyan815 commented Aug 4, 2019 • edited Loading

golang中map是引用类型,应用类型的变量未初始化时默认的zero value是nil。直接向nil map写入键值数据会导致运行时错误

看一个例子:

运行这段程序会出现运行时从错误:

因为在声明 后并未初始化它,所以它的值是nil, 不指向任何内存地址。需要通过 方法分配确定的内存地址。程序修改后即可正常运行:

关于这个问题官方文档中解释如下:


Map types are reference types, like pointers or slices, and so the value of m above is nil; it doesn't point to an initialized map. A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic; don't do that. To initialize a map, use the built in make function:

同为引用类型的slice,在使用 向nil slice追加新元素就可以,原因是 方法在底层为slice重新分配了相关数组让nil slice指向了具体的内存地址

  • 👍 36 reactions
  • 😄 3 reactions
  • 🎉 3 reactions

@odeke-em

fanyingjie11 commented Apr 25, 2022

解答了我的疑惑,thanks

Sorry, something went wrong.

kevinyan815 commented Apr 29, 2022

不客气,很高兴这里的内容能有帮助

  • 👍 2 reactions

No branches or pull requests

@kevinyan815

IMAGES

  1. Assignment To Entry In Nil Map

    golang nested map assignment to entry in nil map

  2. golang assignment to entry in nil map

    golang nested map assignment to entry in nil map

  3. [Solved] structure with nested maps golang

    golang nested map assignment to entry in nil map

  4. Golang Nested Map of Maps

    golang nested map assignment to entry in nil map

  5. 深入解析Golang的map设计

    golang nested map assignment to entry in nil map

  6. How to solve golang error: assignment to entry in nil map-Golang-php.cn

    golang nested map assignment to entry in nil map

VIDEO

  1. Concept Map Explanation

  2. MdZulhaqif_TE27_Em3_AssignmentVideo

  3. Map Assignment 1

  4. Map Assignment 5

  5. Map Assignment 3

  6. Listening Map Assignment

COMMENTS

  1. Runtime error: assignment to entry in nil map

    assignment to entry in nil map For nested maps when assign to the deep level key we needs to be certain that its outer key has value. Else it will say that the map is nil. ... Golang YAML reading with map of maps. 10. Go : assignment to entry in nil map. 1. panic: assignment to entry in nil map on single simple map. 0.

  2. Go : assignment to entry in nil map

    The initial capacity does not bound its size: maps grow to accommodate the number of items stored in them, with the exception of nil maps. A nil map is equivalent to an empty map except that no elements may be added. You write: var countedData map[string][]ChartElement Instead, to initialize the map, write, countedData := make(map[string ...

  3. Golang: How to Assign a Value to an Entry in a Nil Map

    To assign to an entry in a nil map, you can use the following syntax: map [key] = value. For example, the following code will assign the value `"hello"` to the key `"world"` in a nil map: m := make (map [string]string) m ["world"] = "hello". Assignment to entry in a nil map is a dangerous operation that can lead to errors.

  4. Assignment to Entry in Nil Map

    This will cause a panic when we try to assign values to the map. Instead you should use the make keyword as outlined in Solution A. If you are trying to create a series of nested maps (a map similar to a JSON structure, for example), see Solution B. Solutions List. A) Use 'make' to initialize the map. B) Nested maps. Solutions Detail

  5. Go maps in action

    A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic; don't do that. ... The built in delete function removes an entry from the map: delete(m, "route") The delete function doesn't return anything, and will do nothing if the specified key doesn't exist. A two-value assignment tests ...

  6. How to create object map of map(inside map )

    mapData := make (map [string]map [string]int) inner, ok := mapData ["foo"] if !ok {. inner = make (map [string]int) mapData ["foo"] = inner. } inner ["bar"] = 42. If i add the new key value again it will create new nested map but i dont want to new object only one time i will create the nested map object then we can added value ...

  7. Help: Assignment to entry in nil map · YourBasic Go

    panic: assignment to entry in nil map Answer. You have to initialize the map using the make function (or a map literal) before you can add any elements: m := make(map[string]float64) m["pi"] = 3.1416. See Maps explained for more about maps. Index; Next » Share this page: Go Gotchas » Assignment to entry in nil map

  8. Golang error assignment to entry in nil map

    fmt.Println(idx) fmt.Println(key) } The Zero Value of an uninitialized map is nil. Both len and accessing the value of rect ["height"] will work on nil map. len returns 0 and the key of "height" is not found in map and you will get back zero value for int which is 0. Similarly, idx will return 0 and key will return false.

  9. `panic: assignment to entry in nil map` at nested maps : r/golang

    above is i think the minimum you need to change to get your example working. but rather than constructing the map per id and then filling in the keys, just create a map literal and assign it to the id value, something like: var id int. Contests := make(map[string]map[string]map[string]map[string]string)

  10. Nested Maps in Go

    A simple example and the attempt of an explaination. Lets create a simple example to demonstrate the issue at hand: $ go mod init nested_maps. go: creating new go.mod: module nested_maps. $ touch nested_maps.go. Now open nested_maps.go in your favorite editor and paste in the following piece of code: package main import (. "log" "encoding/json ...

  11. Golang Map

    map[] panic: assignment to entry in nil map. Use the make function to create and initialize a map in golang. e.g. my_map = make(map[string]int) In this tutorial, we will discuss golang map, how to create a map in golang, add elements to a map, and delete an element from the map.

  12. plugin: syscall.Mmap panic: assignment to entry in nil map #44491

    If you call syscall.Mmap from your main program, not the plugin, then it will initalise the correct internal structures in the syscall package (or to be more specific, stop the linker stripping them out), and this may work around the problem. 👍 1. Author.

  13. An easier way to initialize the nested map? : r/golang

    If a map entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced. If a map entry is created during iteration, that entry may be produced during the iteration or may be skipped. The choice may vary for each entry created and from one iteration to the next. If the map is nil, the ...

  14. go

    50.3k 3 46 65. 1. Technically this is the 2-value form of the type assertion, not the map lookup. The nil interface value from the map is passed to the assertion which can then assert the interface to the desired zero value. - JimB. Mar 7, 2021 at 20:47. @JimB, you are correct I fixed the answer. - Burak Serdar.

  15. 不要向nil map写入(panic: assignment to entry in nil map) #7

    A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic; don't do that. To initialize a map, use the built in make function: m = make(map[string]int) 同为引用类型的slice,在使用 append 向nil slice追加新元素就可以,原因是 append 方法在底层为slice ...