Assignment to entry in nil map

golang assignment to nil map (sa5000)

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.

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 pronounce missile: a guide for english learners.

How to Pronounce Missile The word “missile” is often mispronounced, with many people saying it as “miss-ile”. However, the correct pronunciation is actually “miss-uh-l”. This article will provide a brief overview of the history of the word “missile” and how it came to be pronounced the way it is today. It will also provide some…

How to Drop Rows in Pandas Based on a Condition

Pandas Drop Rows with Condition In this tutorial, you will learn how to drop rows from a pandas DataFrame based on a condition. You will learn how to use the `drop()` method, the `isin()` function, and the `query()` method. We will use a real-world dataset of housing prices in California to demonstrate the different methods….

How to Use Sidon’s Ability Tears of the Kingdom

How to Use Sidon’s Ability Tears of the Kingdom In the world of The Legend of Zelda: Breath of the Wild, Sidon is a Zora prince who wields the powerful ability Tears of the Kingdom. This ability allows him to create a massive wave of water that can damage enemies, knock them off their feet,…

How to Beat Round 100 Deflation in Cookie Clicker

How to Beat Round 100 Deflation in Bloons TD6 Round 100 deflation is one of the most challenging rounds in Bloons TD6. It’s a test of your ability to create a powerful defense that can withstand an onslaught of powerful bloons. In this article, I’ll share some tips and strategies that will help you beat…

How to Convert WEBP to JPG with FFmpeg

Have you ever wanted to convert a WEBP image to a JPG? If so, you’re in luck! FFmpeg is a free and open-source software that can be used to convert between different image formats. In this article, we’ll show you how to use FFmpeg to convert WEBP images to JPGs. We’ll start by explaining what…

How to Process Triggers for Man-db

Processing Triggers for Man-db Man-db is a utility that provides a hierarchical database of Linux manual pages. It is used to generate the man pages that are displayed when you type the command `man` followed by the name of a command or utility. Man-db also provides a number of triggers that can be used to…

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

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

SA – staticcheck

The SA category of checks, codenamed staticcheck , contains all checks that are concerned with the correctness of code.

SA1 – Various misuses of the standard library

Checks in this category deal with misuses of the standard library. This tends to involve incorrect function arguments or violating other invariants laid out by the standard library's documentation.

SA1000 - Invalid regular expression

Sa1001 - invalid template, sa1002 - invalid format in time.parse, sa1003 - unsupported argument to functions in encoding/binary.

The encoding/binary package can only serialize types with known sizes. This precludes the use of the int and uint types, as their sizes differ on different architectures. Furthermore, it doesn’t support serializing maps, channels, strings, or functions.

Before Go 1.8, bool wasn’t supported, either.

SA1004 - Suspiciously small untyped constant in time.Sleep

The time .Sleep function takes a time.Duration as its only argument. Durations are expressed in nanoseconds. Thus, calling time.Sleep(1) will sleep for 1 nanosecond. This is a common source of bugs, as sleep functions in other languages often accept seconds or milliseconds.

The time package provides constants such as time.Second to express large durations. These can be combined with arithmetic to express arbitrary durations, for example 5 * time.Second for 5 seconds.

If you truly meant to sleep for a tiny amount of time, use n * time.Nanosecond to signal to Staticcheck that you did mean to sleep for some amount of nanoseconds.

SA1005 - Invalid first argument to exec.Command

os/exec runs programs directly (using variants of the fork and exec system calls on Unix systems). This shouldn’t be confused with running a command in a shell. The shell will allow for features such as input redirection, pipes, and general scripting. The shell is also responsible for splitting the user’s input into a program name and its arguments. For example, the equivalent to

If you want to run a command in a shell, consider using something like the following – but be aware that not all systems, particularly Windows, will have a /bin/sh program:

SA1006 - Printf with dynamic first argument and no further arguments

Using fmt.Printf with a dynamic first argument can lead to unexpected output. The first argument is a format string, where certain character combinations have special meaning. If, for example, a user were to enter a string such as

and you printed it with

it would lead to the following output:

Similarly, forming the first parameter via string concatenation with user input should be avoided for the same reason. When printing user input, either use a variant of fmt.Print , or use the %s Printf verb and pass the string as an argument.

SA1007 - Invalid URL in net/url.Parse

Sa1008 - non-canonical key in http.header map.

Keys in http.Header maps are canonical, meaning they follow a specific combination of uppercase and lowercase letters. Methods such as http.Header.Add and http.Header.Del convert inputs into this canonical form before manipulating the map.

When manipulating http.Header maps directly, as opposed to using the provided methods, care should be taken to stick to canonical form in order to avoid inconsistencies. The following piece of code demonstrates one such inconsistency:

The easiest way of obtaining the canonical form of a key is to use http.CanonicalHeaderKey .

SA1010 - (*regexp.Regexp).FindAll called with n == 0 , which will always return zero results

If n >= 0 , the function returns at most n matches/submatches. To return all results, specify a negative number.

SA1011 - Various methods in the strings package expect valid UTF-8, but invalid input is provided

Sa1012 - a nil context.context is being passed to a function, consider using context.todo instead, sa1013 - io.seeker.seek is being called with the whence constant as the first argument, but it should be the second, sa1014 - non-pointer value passed to unmarshal or decode, sa1015 - using time.tick in a way that will leak. consider using time.newticker , and only use time.tick in tests, commands and endless functions, sa1016 - trapping a signal that cannot be trapped.

Not all signals can be intercepted by a process. Specifically, on UNIX-like systems, the syscall.SIGKILL and syscall.SIGSTOP signals are never passed to the process, but instead handled directly by the kernel. It is therefore pointless to try and handle these signals.

SA1017 - Channels used with os/signal.Notify should be buffered

The os/signal package uses non-blocking channel sends when delivering signals. If the receiving end of the channel isn’t ready and the channel is either unbuffered or full, the signal will be dropped. To avoid missing signals, the channel should be buffered and of the appropriate size. For a channel used for notification of just one signal value, a buffer of size 1 is sufficient.

SA1018 - strings.Replace called with n == 0 , which does nothing

With n == 0 , zero instances will be replaced. To replace all instances, use a negative number, or use strings.ReplaceAll .

SA1019 - Using a deprecated function, variable, constant or field

Sa1020 - using an invalid host:port pair with a net.listen -related function, sa1021 - using bytes.equal to compare two net.ip.

A net.IP stores an IPv4 or IPv6 address as a slice of bytes. The length of the slice for an IPv4 address, however, can be either 4 or 16 bytes long, using different ways of representing IPv4 addresses. In order to correctly compare two net.IP s, the net.IP.Equal method should be used, as it takes both representations into account.

SA1023 - Modifying the buffer in an io.Writer implementation

Write must not modify the slice data, even temporarily.

SA1024 - A string cutset contains duplicate characters

The strings.TrimLeft and strings.TrimRight functions take cutsets, not prefixes. A cutset is treated as a set of characters to remove from a string. For example,

will result in the string "word" – any characters that are 1, 2, 3 or 4 are cut from the left of the string.

In order to remove one string from another, use strings.TrimPrefix instead.

SA1025 - It is not possible to use (*time.Timer).Reset ’s return value correctly

Sa1026 - cannot marshal channels or functions, sa1027 - atomic access to 64-bit variable must be 64-bit aligned.

On ARM, x86-32, and 32-bit MIPS, it is the caller’s responsibility to arrange for 64-bit alignment of 64-bit words accessed atomically. The first word in a variable or in an allocated struct, array, or slice can be relied upon to be 64-bit aligned.

You can use the structlayout tool to inspect the alignment of fields in a struct.

SA1028 - sort.Slice can only be used on slices

The first argument of sort.Slice must be a slice.

SA1029 - Inappropriate key in call to context.WithValue

The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context. Users of WithValue should define their own types for keys.

To avoid allocating when assigning to an interface{} , context keys often have concrete type struct{} . Alternatively, exported context key variables’ static type should be a pointer or interface.

SA1030 - Invalid argument in call to a strconv function

This check validates the format, number base and bit size arguments of the various parsing and formatting functions in strconv .

SA2 – Concurrency issues

Checks in this category find concurrency bugs.

SA2000 - sync.WaitGroup.Add called inside the goroutine, leading to a race condition

Sa2001 - empty critical section, did you mean to defer the unlock.

Empty critical sections of the kind

are very often a typo, and the following was intended instead:

Do note that sometimes empty critical sections can be useful, as a form of signaling to wait on another goroutine. Many times, there are simpler ways of achieving the same effect. When that isn’t the case, the code should be amply commented to avoid confusion. Combining such comments with a //lint:ignore directive can be used to suppress this rare false positive.

SA2002 - Called testing.T.FailNow or SkipNow in a goroutine, which isn’t allowed

Sa2003 - deferred lock right after locking, likely meant to defer unlock instead, sa3 – testing issues.

Checks in this category find issues in tests and benchmarks.

SA3000 - TestMain doesn’t call os.Exit , hiding test failures

Test executables (and in turn go test ) exit with a non-zero status code if any tests failed. When specifying your own TestMain function, it is your responsibility to arrange for this, by calling os.Exit with the correct code. The correct code is returned by (*testing.M).Run , so the usual way of implementing TestMain is to end it with os.Exit(m.Run()) .

SA3001 - Assigning to b.N in benchmarks distorts the results

The testing package dynamically sets b.N to improve the reliability of benchmarks and uses it in computations to determine the duration of a single operation. Benchmark code must not alter b.N as this would falsify results.

SA4 – Code that isn't really doing anything

Checks in this category point out code that doesn't have any meaningful effect on a program's execution. Usually this means that the programmer thought the code would do one thing while in reality it does something else.

SA4000 - Binary operator has identical expressions on both sides

Sa4001 - &*x gets simplified to x , it does not copy x, sa4003 - comparing unsigned values against negative values is pointless, sa4004 - the loop exits unconditionally after one iteration, sa4005 - field assignment that will never be observed. did you mean to use a pointer receiver, sa4006 - a value assigned to a variable is never read before being overwritten. forgotten error check or dead code, sa4008 - the variable in the loop condition never changes, are you incrementing the wrong variable, sa4009 - a function argument is overwritten before its first use, sa4010 - the result of append will never be observed anywhere, sa4011 - break statement with no effect. did you mean to break out of an outer loop, sa4012 - comparing a value against nan even though no value is equal to nan, sa4013 - negating a boolean twice ( b ) is the same as writing b . this is either redundant, or a typo., sa4014 - an if/else if chain has repeated conditions and no side-effects; if the condition didn’t match the first time, it won’t match the second time, either, sa4015 - calling functions like math.ceil on floats converted from integers doesn’t do anything useful, sa4016 - certain bitwise operations, such as x ^ 0 , do not do anything useful, sa4017 - discarding the return values of a function without side effects, making the call pointless, sa4018 - self-assignment of variables, sa4019 - multiple, identical build constraints in the same file, sa4020 - unreachable case clause in a type switch.

In a type switch like the following

the second case clause can never be reached because T implements io.Reader and case clauses are evaluated in source order.

Another example:

Even though T has a Close method and thus implements io.ReadCloser , io.Reader will always match first. The method set of io.Reader is a subset of io.ReadCloser . Thus it is impossible to match the second case without matching the first case.

Structurally equivalent interfaces

A special case of the previous example are structurally identical interfaces. Given these declarations

the following type switch will have an unreachable case clause:

T will always match before V because they are structurally equivalent and therefore doSomething() ’s return value implements both.

SA4021 - x = append(y) is equivalent to x = y

Sa4022 - comparing the address of a variable against nil.

Code such as if &x == nil is meaningless, because taking the address of a variable always yields a non-nil pointer.

SA4023 - Impossible comparison of interface value with untyped nil

Under the covers, interfaces are implemented as two elements, a type T and a value V. V is a concrete value such as an int, struct or pointer, never an interface itself, and has type T. For instance, if we store the int value 3 in an interface, the resulting interface value has, schematically, (T=int, V=3). The value V is also known as the interface’s dynamic value, since a given interface variable might hold different values V (and corresponding types T) during the execution of the program.

An interface value is nil only if the V and T are both unset, (T=nil, V is not set), In particular, a nil interface will always hold a nil type. If we store a nil pointer of type *int inside an interface value, the inner type will be *int regardless of the value of the pointer: (T=*int, V=nil). Such an interface value will therefore be non-nil even when the pointer value V inside is nil.

This situation can be confusing, and arises when a nil value is stored inside an interface value such as an error return:

If all goes well, the function returns a nil p, so the return value is an error interface value holding (T=*MyError, V=nil). This means that if the caller compares the returned error to nil, it will always look as if there was an error even if nothing bad happened. To return a proper nil error to the caller, the function must return an explicit nil:

It’s a good idea for functions that return errors always to use the error type in their signature (as we did above) rather than a concrete type such as *MyError , to help guarantee the error is created correctly. As an example, os.Open returns an error even though, if not nil, it’s always of concrete type *os.PathError.

Similar situations to those described here can arise whenever interfaces are used. Just keep in mind that if any concrete value has been stored in the interface, the interface will not be nil. For more information, see The Laws of Reflection ( https://golang.org/doc/articles/laws_of_reflection.html) .

This text has been copied from https://golang.org/doc/faq#nil_error , licensed under the Creative Commons Attribution 3.0 License.

SA4024 - Checking for impossible return value from a builtin function

Return values of the len and cap builtins cannot be negative.

See https://golang.org/pkg/builtin/#len and https://golang.org/pkg/builtin/#cap .

SA4025 - Integer division of literals that results in zero

When dividing two integer constants, the result will also be an integer. Thus, a division such as 2 / 3 results in 0 . This is true for all of the following examples:

Staticcheck will flag such divisions if both sides of the division are integer literals, as it is highly unlikely that the division was intended to truncate to zero. Staticcheck will not flag integer division involving named constants, to avoid noisy positives.

SA4026 - Go constants cannot express negative zero

In IEEE 754 floating point math, zero has a sign and can be positive or negative. This can be useful in certain numerical code.

Go constants, however, cannot express negative zero. This means that the literals -0.0 and 0.0 have the same ideal value (zero) and will both represent positive zero at runtime.

To explicitly and reliably create a negative zero, you can use the math.Copysign function: math.Copysign(0, -1) .

SA4027 - (*net/url.URL).Query returns a copy, modifying it doesn’t change the URL

(*net/url.URL).Query parses the current value of net/url.URL.RawQuery and returns it as a map of type net/url.Values . Subsequent changes to this map will not affect the URL unless the map gets encoded and assigned to the URL’s RawQuery .

As a consequence, the following code pattern is an expensive no-op: u.Query().Add(key, value) .

SA4028 - x % 1 is always zero

Sa4029 - ineffective attempt at sorting slice.

sort.Float64Slice , sort.IntSlice , and sort.StringSlice are types, not functions. Doing x = sort.StringSlice(x) does nothing, especially not sort any values. The correct usage is sort.Sort(sort.StringSlice(x)) or sort.StringSlice(x).Sort() , but there are more convenient helpers, namely sort.Float64s , sort.Ints , and sort.Strings .

SA4030 - Ineffective attempt at generating random number

Functions in the math/rand package that accept upper limits, such as Intn , generate random numbers in the half-open interval [0,n). In other words, the generated numbers will be >= 0 and < n – they don’t include n . rand.Intn(1) therefore doesn’t generate 0 or 1 , it always generates 0 .

SA4031 - Checking never-nil value against nil

Sa5 – correctness issues.

Checks in this category find assorted bugs and crashes.

SA5000 - Assignment to nil map

Sa5001 - deferring close before checking for a possible error, sa5002 - the empty for loop ( for {} ) spins and can block the scheduler, sa5003 - defers in infinite loops will never execute.

Defers are scoped to the surrounding function, not the surrounding block. In a function that never returns, i.e. one containing an infinite loop, defers will never execute.

SA5004 - for { select { ... with an empty default branch spins

Sa5005 - the finalizer references the finalized object, preventing garbage collection.

A finalizer is a function associated with an object that runs when the garbage collector is ready to collect said object, that is when the object is no longer referenced by anything.

If the finalizer references the object, however, it will always remain as the final reference to that object, preventing the garbage collector from collecting the object. The finalizer will never run, and the object will never be collected, leading to a memory leak. That is why the finalizer should instead use its first argument to operate on the object. That way, the number of references can temporarily go to zero before the object is being passed to the finalizer.

SA5007 - Infinite recursive call

A function that calls itself recursively needs to have an exit condition. Otherwise it will recurse forever, until the system runs out of memory.

This issue can be caused by simple bugs such as forgetting to add an exit condition. It can also happen “on purpose”. Some languages have tail call optimization which makes certain infinite recursive calls safe to use. Go, however, does not implement TCO, and as such a loop should be used instead.

SA5008 - Invalid struct tag

Sa5009 - invalid printf call, sa5010 - impossible type assertion.

Some type assertions can be statically proven to be impossible. This is the case when the method sets of both arguments of the type assertion conflict with each other, for example by containing the same method with different signatures.

The Go compiler already applies this check when asserting from an interface value to a concrete type. If the concrete type misses methods from the interface, or if function signatures don’t match, then the type assertion can never succeed.

This check applies the same logic when asserting from one interface to another. If both interface types contain the same method but with different signatures, then the type assertion can never succeed, either.

SA5011 - Possible nil pointer dereference

A pointer is being dereferenced unconditionally, while also being checked against nil in another place. This suggests that the pointer may be nil and dereferencing it may panic. This is commonly a result of improperly ordered code or missing return statements. Consider the following examples:

Staticcheck tries to deduce which functions abort control flow. For example, it is aware that a function will not continue execution after a call to panic or log.Fatal . However, sometimes this detection fails, in particular in the presence of conditionals. Consider the following example:

Staticcheck will flag the dereference of x , even though it is perfectly safe. Staticcheck is not able to deduce that a call to Fatal will exit the program. For the time being, the easiest workaround is to modify the definition of Fatal like so:

We also hard-code functions from common logging packages such as logrus. Please file an issue if we’re missing support for a popular package.

SA5012 - Passing odd-sized slice to function expecting even size

Some functions that take slices as parameters expect the slices to have an even number of elements. Often, these functions treat elements in a slice as pairs. For example, strings.NewReplacer takes pairs of old and new strings, and calling it with an odd number of elements would be an error.

SA6 – Performance issues

Checks in this category find code that can be trivially made faster.

SA6000 - Using regexp.Match or related in a loop, should use regexp.Compile

Sa6001 - missing an optimization opportunity when indexing maps by byte slices.

Map keys must be comparable, which precludes the use of byte slices. This usually leads to using string keys and converting byte slices to strings.

Normally, a conversion of a byte slice to a string needs to copy the data and causes allocations. The compiler, however, recognizes m[string(b)] and uses the data of b directly, without copying it, because it knows that the data can’t change during the map lookup. This leads to the counter-intuitive situation that

will be less efficient than

because the first version needs to copy and allocate, while the second one does not.

For some history on this optimization, check out commit f5f5a8b6209f84961687d993b93ea0d397f5d5bf in the Go repository.

SA6002 - Storing non-pointer values in sync.Pool allocates memory

A sync.Pool is used to avoid unnecessary allocations and reduce the amount of work the garbage collector has to do.

When passing a value that is not a pointer to a function that accepts an interface, the value needs to be placed on the heap, which means an additional allocation. Slices are a common thing to put in sync.Pools, and they’re structs with 3 fields (length, capacity, and a pointer to an array). In order to avoid the extra allocation, one should store a pointer to the slice instead.

See the comments on https://go-review.googlesource.com/c/go/+/24371 that discuss this problem.

SA6003 - Converting a string to a slice of runes before ranging over it

You may want to loop over the runes in a string. Instead of converting the string to a slice of runes and looping over that, you can loop over the string itself. That is,

will yield the same values. The first version, however, will be faster and avoid unnecessary memory allocations.

Do note that if you are interested in the indices, ranging over a string and over a slice of runes will yield different indices. The first one yields byte offsets, while the second one yields indices in the slice of runes.

SA6005 - Inefficient string comparison with strings.ToLower or strings.ToUpper

Converting two strings to the same case and comparing them like so

is significantly more expensive than comparing them with strings.EqualFold(s1, s2) . This is due to memory usage as well as computational complexity.

strings.ToLower will have to allocate memory for the new strings, as well as convert both strings fully, even if they differ on the very first byte. strings.EqualFold, on the other hand, compares the strings one character at a time. It doesn’t need to create two intermediate strings and can return as soon as the first non-matching character has been found.

For a more in-depth explanation of this issue, see https://blog.digitalocean.com/how-to-efficiently-compare-strings-in-go/

SA9 – Dubious code constructs that have a high probability of being wrong

Checks in this category find code that is probably wrong. Unlike checks in the other SA categories, checks in SA9 have a slight chance of reporting false positives. However, even false positives will point at code that is confusing and that should probably be refactored.

SA9001 - Defers in range loops may not run when you expect them to

Sa9002 - using a non-octal os.filemode that looks like it was meant to be in octal., sa9003 - empty body in an if or else branch, sa9004 - only the first constant has an explicit type.

In a constant declaration such as the following:

the constant Second does not have the same type as the constant First. This construct shouldn’t be confused with

where First and Second do indeed have the same type. The type is only passed on when no explicit value is assigned to the constant.

When declaring enumerations with explicit values it is therefore important not to write

This discrepancy in types can cause various confusing behaviors and bugs.

Wrong type in variable declarations

The most obvious issue with such incorrect enumerations expresses itself as a compile error:

fails to compile with

Losing method sets

A more subtle issue occurs with types that have methods and optional interfaces. Consider the following:

This code will output

as EnumSecond has no explicit type, and thus defaults to int .

SA9005 - Trying to marshal a struct with no public fields nor custom marshaling

The encoding/json and encoding/xml packages only operate on exported fields in structs, not unexported ones. It is usually an error to try to (un)marshal structs that only consist of unexported fields.

This check will not flag calls involving types that define custom marshaling behavior, e.g. via MarshalJSON methods. It will also not flag empty structs.

SA9006 - Dubious bit shifting of a fixed size integer value

Bit shifting a value past its size will always clear the value.

For instance:

will always result in 0.

This check flags bit shifting operations on fixed size integer values only. That is, int, uint and uintptr are never flagged to avoid potential false positives in somewhat exotic but valid bit twiddling tricks:

SA9007 - Deleting a directory that shouldn’t be deleted

It is virtually never correct to delete system directories such as /tmp or the user’s home directory. However, it can be fairly easy to do by mistake, for example by mistakingly using os.TempDir instead of ioutil.TempDir , or by forgetting to add a suffix to the result of os.UserHomeDir .

in your unit tests will have a devastating effect on the stability of your system.

This check flags attempts at deleting the following directories:

  • os.UserCacheDir
  • os.UserConfigDir
  • os.UserHomeDir

SA9008 - else branch of a type assertion is probably not reading the right value

When declaring variables as part of an if statement (like in if foo := ...; foo { ), the same variables will also be in the scope of the else branch. This means that in the following example

x in the else branch will refer to the x from x, ok := ; it will not refer to the x that is being type-asserted. The result of a failed type assertion is the zero value of the type that is being asserted to, so x in the else branch will always have the value 0 and the type int .

The S category of checks, codenamed simple , contains all checks that are concerned with simplifying code.

S1 – Code simplifications

Checks in this category find code that is unnecessarily complex and that can be trivially simplified.

S1000 - Use plain channel send or receive instead of single-case select

Select statements with a single case can be replaced with a simple send or receive.

S1001 - Replace for loop with call to copy

Use copy() for copying elements from one slice to another. For arrays of identical size, you can use simple assignment.

S1002 - Omit comparison with boolean constant

S1003 - replace call to strings.index with strings.contains, s1004 - replace call to bytes.compare with bytes.equal, s1005 - drop unnecessary use of the blank identifier.

In many cases, assigning to the blank identifier is unnecessary.

S1006 - Use for { ... } for infinite loops

For infinite loops, using for { ... } is the most idiomatic choice.

S1007 - Simplify regular expression by using raw string literal

Raw string literals use backticks instead of quotation marks and do not support any escape sequences. This means that the backslash can be used freely, without the need of escaping.

Since regular expressions have their own escape sequences, raw strings can improve their readability.

S1008 - Simplify returning boolean expression

S1009 - omit redundant nil check on slices.

The len function is defined for all slices, even nil ones, which have a length of zero. It is not necessary to check if a slice is not nil before checking that its length is not zero.

S1010 - Omit default slice index

When slicing, the second index defaults to the length of the value, making s[n:len(s)] and s[n:] equivalent.

S1011 - Use a single append to concatenate two slices

S1012 - replace time.now().sub(x) with time.since(x).

The time.Since helper has the same effect as using time.Now().Sub(x) but is easier to read.

S1016 - Use a type conversion instead of manually copying struct fields

Two struct types with identical fields can be converted between each other. In older versions of Go, the fields had to have identical struct tags. Since Go 1.8, however, struct tags are ignored during conversions. It is thus not necessary to manually copy every field individually.

S1017 - Replace manual trimming with strings.TrimPrefix

Instead of using strings.HasPrefix and manual slicing, use the strings.TrimPrefix function. If the string doesn’t start with the prefix, the original string will be returned. Using strings.TrimPrefix reduces complexity, and avoids common bugs, such as off-by-one mistakes.

S1018 - Use copy for sliding elements

copy() permits using the same source and destination slice, even with overlapping ranges. This makes it ideal for sliding elements in a slice.

S1019 - Simplify make call by omitting redundant arguments

The make function has default values for the length and capacity arguments. For channels, the length defaults to zero, and for slices, the capacity defaults to the length.

S1020 - Omit redundant nil check in type assertion

S1021 - merge variable declaration and assignment, s1023 - omit redundant control flow.

Functions that have no return value do not need a return statement as the final statement of the function.

Switches in Go do not have automatic fallthrough, unlike languages like C. It is not necessary to have a break statement as the final statement in a case block.

S1024 - Replace x.Sub(time.Now()) with time.Until(x)

The time.Until helper has the same effect as using x.Sub(time.Now()) but is easier to read.

S1025 - Don’t use fmt.Sprintf("%s", x) unnecessarily

In many instances, there are easier and more efficient ways of getting a value’s string representation. Whenever a value’s underlying type is a string already, or the type has a String method, they should be used directly.

Given the following shared definitions

we can simplify

S1028 - Simplify error construction with fmt.Errorf

S1029 - range over the string directly.

Ranging over a string will yield byte offsets and runes. If the offset isn’t used, this is functionally equivalent to converting the string to a slice of runes and ranging over that. Ranging directly over the string will be more performant, however, as it avoids allocating a new slice, the size of which depends on the length of the string.

S1030 - Use bytes.Buffer.String or bytes.Buffer.Bytes

bytes.Buffer has both a String and a Bytes method. It is almost never necessary to use string(buf.Bytes()) or []byte(buf.String()) – simply use the other method.

The only exception to this are map lookups. Due to a compiler optimization, m[string(buf.Bytes())] is more efficient than m[buf.String()] .

S1031 - Omit redundant nil check around loop

You can use range on nil slices and maps, the loop will simply never execute. This makes an additional nil check around the loop unnecessary.

S1032 - Use sort.Ints(x) , sort.Float64s(x) , and sort.Strings(x)

The sort.Ints , sort.Float64s and sort.Strings functions are easier to read than sort.Sort(sort.IntSlice(x)) , sort.Sort(sort.Float64Slice(x)) and sort.Sort(sort.StringSlice(x)) .

S1033 - Unnecessary guard around call to delete

Calling delete on a nil map is a no-op.

S1034 - Use result of type assertion to simplify cases

S1035 - redundant call to net/http.canonicalheaderkey in method call on net/http.header.

The methods on net/http.Header , namely Add , Del , Get and Set , already canonicalize the given header name.

S1036 - Unnecessary guard around map access

When accessing a map key that doesn’t exist yet, one receives a zero value. Often, the zero value is a suitable value, for example when using append or doing integer math.

The following

can be simplified to

S1037 - Elaborate way of sleeping

Using a select statement with a single case receiving from the result of time.After is a very elaborate way of sleeping that can much simpler be expressed with a simple call to time.Sleep.

S1038 - Unnecessarily complex way of printing formatted string

Instead of using fmt.Print(fmt.Sprintf(...)) , one can use fmt.Printf(...) .

S1039 - Unnecessary use of fmt.Sprint

Calling fmt.Sprint with a single string argument is unnecessary and identical to using the string directly.

S1040 - Type assertion to current type

The type assertion x.(SomeInterface) , when x already has type SomeInterface , can only fail if x is nil. Usually, this is left-over code from when x had a different type and you can safely delete the type assertion. If you want to check that x is not nil, consider being explicit and using an actual if x == nil comparison instead of relying on the type assertion panicking.

ST – stylecheck

The ST category of checks, codenamed stylecheck , contains all checks that are concerned with stylistic issues.

ST1 – Stylistic issues

The rules contained in this category are primarily derived from the Go wiki and represent community consensus.

Some checks are very pedantic and disabled by default. You may want to tweak which checks from this category run , based on your project's needs.

ST1000 - Incorrect or missing package comment non-default

Packages must have a package comment that is formatted according to the guidelines laid out in https://github.com/golang/go/wiki/CodeReviewComments#package-comments .

ST1001 - Dot imports are discouraged

Dot imports that aren’t in external test packages are discouraged.

The dot_import_whitelist option can be used to whitelist certain imports.

Quoting Go Code Review Comments:

The import . form can be useful in tests that, due to circular dependencies, cannot be made part of the package being tested: package foo_test import ( "bar/testutil" // also imports "foo" . "foo" ) In this case, the test file cannot be in package foo because it uses bar/testutil , which imports foo . So we use the import . form to let the file pretend to be part of package foo even though it is not. Except for this one case, do not use import . in your programs. It makes the programs much harder to read because it is unclear whether a name like Quux is a top-level identifier in the current package or in an imported package.
  • dot_import_whitelist

ST1003 - Poorly chosen identifier non-default

Identifiers, such as variable and package names, follow certain rules.

See the following links for details:

  • https://golang.org/doc/effective_go.html#package-names
  • https://golang.org/doc/effective_go.html#mixed-caps
  • https://github.com/golang/go/wiki/CodeReviewComments#initialisms
  • https://github.com/golang/go/wiki/CodeReviewComments#variable-names
  • initialisms

ST1005 - Incorrectly formatted error string

Error strings follow a set of guidelines to ensure uniformity and good composability.

Error strings should not be capitalized (unless beginning with proper nouns or acronyms) or end with punctuation, since they are usually printed following other context. That is, use fmt.Errorf("something bad") not fmt.Errorf("Something bad") , so that log.Printf("Reading %s: %v", filename, err) formats without a spurious capital letter mid-message.

ST1006 - Poorly chosen receiver name

The name of a method’s receiver should be a reflection of its identity; often a one or two letter abbreviation of its type suffices (such as “c” or “cl” for “Client”). Don’t use generic names such as “me”, “this” or “self”, identifiers typical of object-oriented languages that place more emphasis on methods as opposed to functions. The name need not be as descriptive as that of a method argument, as its role is obvious and serves no documentary purpose. It can be very short as it will appear on almost every line of every method of the type; familiarity admits brevity. Be consistent, too: if you call the receiver “c” in one method, don’t call it “cl” in another.

ST1008 - A function’s error value should be its last return value

A function’s error value should be its last return value.

ST1011 - Poorly chosen name for variable of type time.Duration

time.Duration values represent an amount of time, which is represented as a count of nanoseconds. An expression like 5 * time.Microsecond yields the value 5000 . It is therefore not appropriate to suffix a variable of type time.Duration with any time unit, such as Msec or Milli .

ST1012 - Poorly chosen name for error variable

Error variables that are part of an API should be called errFoo or ErrFoo .

ST1013 - Should use constants for HTTP error codes, not magic numbers

HTTP has a tremendous number of status codes. While some of those are well known (200, 400, 404, 500), most of them are not. The net/http package provides constants for all status codes that are part of the various specifications. It is recommended to use these constants instead of hard-coding magic numbers, to vastly improve the readability of your code.

  • http_status_code_whitelist

ST1015 - A switch’s default case should be the first or last case

St1016 - use consistent method receiver names non-default, st1017 - don’t use yoda conditions.

Yoda conditions are conditions of the kind if 42 == x , where the literal is on the left side of the comparison. These are a common idiom in languages in which assignment is an expression, to avoid bugs of the kind if (x = 42) . In Go, which doesn’t allow for this kind of bug, we prefer the more idiomatic if x == 42 .

ST1018 - Avoid zero-width and control characters in string literals

St1019 - importing the same package multiple times.

Go allows importing the same package multiple times, as long as different import aliases are being used. That is, the following bit of code is valid:

However, this is very rarely done on purpose. Usually, it is a sign of code that got refactored, accidentally adding duplicate import statements. It is also a rarely known feature, which may contribute to confusion.

Do note that sometimes, this feature may be used intentionally (see for example https://github.com/golang/go/commit/3409ce39bfd7584523b7a8c150a310cea92d879d ) – if you want to allow this pattern in your code base, you’re advised to disable this check.

ST1020 - The documentation of an exported function should start with the function’s name non-default

Doc comments work best as complete sentences, which allow a wide variety of automated presentations. The first sentence should be a one-sentence summary that starts with the name being declared.

If every doc comment begins with the name of the item it describes, you can use the doc subcommand of the go tool and run the output through grep.

See https://golang.org/doc/effective_go.html#commentary for more information on how to write good documentation.

ST1021 - The documentation of an exported type should start with type’s name non-default

St1022 - the documentation of an exported variable or constant should start with variable’s name non-default, st1023 - redundant type in variable declaration non-default, qf – quickfix.

The QF category of checks, codenamed quickfix , contains checks that are used as part of gopls for automatic refactorings. In the context of gopls, diagnostics of these checks will usually show up as hints, sometimes as information-level diagnostics.

QF1 – Quickfixes

Qf1001 - apply de morgan’s law, qf1002 - convert untagged switch to tagged switch.

An untagged switch that compares a single variable against a series of values can be replaced with a tagged switch.

QF1003 - Convert if/else-if chain to tagged switch

A series of if/else-if checks comparing the same variable against values can be replaced with a tagged switch.

QF1004 - Use strings.ReplaceAll instead of strings.Replace with n == -1

Qf1005 - expand call to math.pow.

Some uses of math.Pow can be simplified to basic multiplication.

QF1006 - Lift if + break into loop condition

Qf1007 - merge conditional assignment into variable declaration, qf1008 - omit embedded fields from selector expression, qf1009 - use time.time.equal instead of == operator, qf1010 - convert slice of bytes to string when printing it, qf1011 - omit redundant type from variable declaration, qf1012 - use fmt.fprintf(x, ...) instead of x.write(fmt.sprintf(...)).

golang assignment to nil map (sa5000)

assignment to nil map golang

Code examples.

  • answer assignment to nil map golang

More Related Answers

  • panic: assignment to entry in nil map
  • go add to map
  • Go Map in Golang
  • Go Change value of a map in Golang
  • Assignment Operator in Go
  • declare variable without assignment in go

Answers Matrix View Full Screen

golang assignment to nil map (sa5000)

Documentation

Twitter Logo

Oops, You will need to install Grepper and log-in to perform this action.

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

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

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

@odeke-em

fanyingjie11 commented Apr 25, 2022

Sorry, something went wrong.

kevinyan815 commented Apr 29, 2022

  • 👍 1 reaction

No branches or pull requests

@kevinyan815

IMAGES

  1. 【Golang】Assignment to entry in nil map

    golang assignment to nil map (sa5000)

  2. Learn Maps in Golang (with examples)

    golang assignment to nil map (sa5000)

  3. The Supreme Guide to Golang Maps

    golang assignment to nil map (sa5000)

  4. Golang map实践以及实现原理_go 返回空 map-CSDN博客

    golang assignment to nil map (sa5000)

  5. The Supreme Guide to Golang Maps

    golang assignment to nil map (sa5000)

  6. 深入解析Golang的map设计

    golang assignment to nil map (sa5000)

VIDEO

  1. Gorkhpur Airport ✈️✈️ll Steem Train 🚂🚂

  2. RoWar Team Battle. Space Cruise Secrets/Glitches

  3. ADDON DAN MAP ATTACK ON TITAN MCPE/MINECRAFT BEDROCK

  4. Golang. Map

  5. IFM SA5000 / ifm Flow sensor SA5000

  6. Terra Nil

COMMENTS

  1. Go : assignment to entry in nil map

    Map types. A new, empty map value is made using the built-in function make, which takes the map type and an optional capacity hint as arguments: make(map[string]int) make(map[string]int, 100) 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.

  2. Runtime error: assignment to entry in nil map

    @Makpoc already answered the question. Here is some extra info from the Go Blog. (In the quote, m refers to an example from the blogpost. In this case, the problem is not m but m["uid"].). 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.

  3. 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

  4. 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.

  5. SA5000: doesn't detect assignment following the return of a nil map or

    Additionally, in the scenario where xxx := doSomething(), if doSomething could potentially return either nil or a map, it seems we don't have a good way to check for this. I wondered if SA5011 stopped doing this type of check because of a high number of false negatives being identified, as mentioned in the Release notes.

  6. Assignment to Entry in Nil Map

    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.

  7. Panic: assignment to entry in nil map for complex struct

    package main import ( "fmt" ) type Plan struct { BufferMeasures map[string]*ItemSiteMeasure } type ItemSiteMeasure struct { itemtest string } func main() { fmt ...

  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. 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.

  10. SA5000: sometimes doesn't detect nil maps #1363

    xy6321 changed the title SA5000: sometimes not working SA5000: sometimes doesn't detect nil maps on Feb 7, 2023. Assignees.

  11. Panic: assignment to entry in nil map

    The above code is being called from main. radovskyb (Benjamin Radovsky) September 2, 2016, 2:53pm 5. frayela: droid [matchId] [droidId] = Match {1, 100} <- this is line trown the Panic: assignment to entry in nil map. Hey @frayela, you need to replace that line with the following for it to work: droid[matchId] = map[string]Match{droidId ...

  12. Checks

    Checking never-nil value against nil: SA5 Correctness issues; SA5000: Assignment to nil map: SA5001: Deferring Close before checking for a possible error: SA5002: The empty for loop (for {}) spins and can block the scheduler: SA5003: Defers in infinite loops will never execute: SA5004: for { select { ... with an empty default branch spins: SA5005

  13. Go Gotcha: Nil Maps

    bankAccounts["123-456"] = 100.00 panic: assignment to entry in nil map Since we didn't initialize the map it is nil by default. Consider this next example; another common mistake.

  14. golang panic: assignment to entry in nil map(map赋值前要先初始化

    目录 Golang中,内建map切忌开箱即用 嵌套场景 golang中的map不是并发安全的 如何解决 或许你可以尝试下sync.Map 引用 Golang中,内建map切忌开箱即用 Golang中,map是引用类型,如指针切片一样,通过下面的代码声明后指向的是nil。

  15. SA5000: doesn't detect nil maps inside loops #855

    dominikh added this to the v2020.3 milestone on Oct 19, 2020. dominikh changed the title SA5000 does not work in some cases SA5000: doesn't detect nil maps inside loops on Oct 19, 2020. dominikh closed this as completed in 5047034 on Dec 29, 2020. dominikh added a commit that referenced this issue on Jan 20, 2021.

  16. assignment to nil map golang

    to avoid runtime error assignment to nil map (SA5000)go-staticcheck m = make(map[string]int)

  17. Assignment to entry in nil map when using http header with Echo golang

    panic: assignment to entry in nil map [recovered] panic: assignment to entry in nil map The panic is on the line in bold (astrix in the code), when Im trying to set the header. What am I doing wrong?

  18. plugin: assignment to nil map (SA5000)go-staticcheck #265

    Saved searches Use saved searches to filter your results more quickly

  19. 不要向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 ...