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

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

Assignment to entry in nil map

assignment to nil map (staticcheck)

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.

Report an Issue.

¿Having technical problems or want to give feedback on the experience? Send us you message and we will get back to you as soon as possible.

Other questions or comments?

Find us in the play-with-go channel at the Gopher's community slack.

How to use and tweak Staticcheck

By Dominik Honnef , author of Staticcheck.

Staticcheck is a state of the art linter for the Go programming language. Using static analysis , it finds bugs and performance issues, offers simplifications, and enforces style rules.

Its checks have been designed to be fast, precise and useful. When Staticcheck flags code, you can be sure that it isn’t wasting your time with unactionable warnings. While checks have been designed to be useful out of the box, they still provide configuration where necessary, to fine-tune to your needs, without overwhelming you with hundreds of options.

Staticcheck can be used from the command line, in continuous integration (CI), and even directly from your editor .

Staticcheck is open source and offered completely free of charge. Sponsors guarantee its continued development. The play-with-go.dev project is proud to sponsor the Staticcheck project. If you, your employer or your company use Staticcheck please consider sponsoring the project.

This guide gets you up and running with Staticcheck by analysing the pets module.

Prerequisites

You should already have completed:

  • Go fundamentals

This guide is running using:

Installing Staticcheck

In this guide you will install Staticcheck to your PATH . For details on how to add development tools as a project module dependency, please see the “Developer tools as module dependencies” guide .

Use go get to install Staticcheck:

Note: so that this guide remains reproducible we have spcified an explicit version, v0.3.3 . When running yourself you could use the special version latest .

The rather ugly use of a temporary directory ensures that go get is run outside of a module. See the “Setting up your PATH “ section in Installing Go to ensure your PATH is set correctly.

Check that staticcheck is on your PATH :

Run staticcheck as a quick check:

You’re all set!

Create the pets module

Time to create an initial version of the pets module:

Because you are not going to publish this module (or import the pets package; it’s just a toy example), you do not need to initialise this directory as a git repository and can give the module whatever path you like. Here, simply pets .

Create an inital version of the pets package in pets.go :

This code looks sensible enough. Build it to confirm there are no compile errors:

All good. Or is it? Let’s run Staticcheck to see what it thinks.

Staticcheck can be run on code in several ways, mimicking the way the official Go tools work. At its core, it expects to be run on well-formed Go packages. So let’s run it on the current package, the pets package:

Oh dear, Staticcheck has found some issues!

As you can see from the output, Staticcheck reports errors much like the Go compiler. Each line represents a problem, starting with a file position, then a description of the problem, with the Staticcheck check number in parentheses at the end of the line.

Staticcheck checks fall into different categories, with each category identified by a different code prefix. Some are listed below:

  • Code simplification S1???
  • Correctness issues SA5???
  • Stylistic issues ST1???

The Staticcheck website lists and documents all the categories and checks . Many of the checks even have examples. You can also use the -explain flag to get details at the command line:

Let’s consider one of the problems reported, ST1006 , documented as “Poorly chosen receiver name”. The Staticcheck check documentation quotes from the Go Code Review Comments wiki :

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.

Each error message explains the problem, but also indicates how to fix the problem. Let’s fix up pets.go :

And re-run Staticcheck to confirm:

Excellent, much better.

Configuring Staticcheck

Staticcheck works out of the box with some sensible, battle-tested defaults. However, various aspects of Staticcheck can be customized with configuration files.

Whilst fixing up the problems Staticcheck reported, you notice that the pets package is missing a package comment. You also happened to notice on the Staticcheck website that check ST1000 covers exactly this case, but that it is not enabled by default.

Staticcheck configuration files are named staticcheck.conf and contain TOML .

Let’s create a Staticcheck configuration file to enable check ST1000 , inheriting from the Staticcheck defaults:

Re-run Staticcheck to verify ST1000 is reported:

Excellent. Add a package comment to pets.go to fix the problem:

Re-run Staticcheck to confirm there are no further problems:

Ignoring problems

Before going much further, you decide it’s probably a good idea to be able to feed a pet, and so make the following change to pets.go :

Re-run Staticcheck to verify all is still fine:

Oops, that was careless. Whilst it’s clear how you would fix this problem (and you really should!), is it possible to tell Staticcheck to ignore problems of this kind?

In general, you shouldn’t have to ignore problems reported by Staticcheck. Great care is taken to minimize the number of false positives and subjective suggestions. Dubious code should be rewritten and genuine false positives should be reported so that they can be fixed.

The reality of things, however, is that not all corner cases can be taken into consideration. Sometimes code just has to look weird enough to confuse tools, and sometimes suggestions, though well-meant, just aren’t applicable. For those rare cases, there are several ways of ignoring unwanted problems.

This is not a rare or corner case, but let’s use it as an opportunity to demonstrate linter directives.

The most fine-grained way of ignoring reported problems is to annotate the offending lines of code with linter directives. Let’s ignore SA4018 using a line directive, updating pets.go :

Verify that Staticcheck no longer complains:

In some cases, however, you may want to disable checks for an entire file. For example, code generation may leave behind a lot of unused code, as it simplifies the generation process. Instead of manually annotating every instance of unused code, the code generator can inject a single, file-wide ignore directive to ignore the problem.

Let’s change the line-based linter directive to a file-based one in pets.go :

Verify that Staticcheck continues to ignore this check:

Great. That’s both line and file-based linter directives covered, demonstrating how to ignore certain problems.

Finally, let’s remove the linter directive, and fix up your code:

And check that Staticcheck is happy one last time:

We can now be sure of lots of happy pets!

This guide has provided you with an introduction to Staticcheck, and the power of static analysis. To learn more see:

  • the “Developer tools as module dependencies” guide guide to see how to add tools like Staticcheck to a project.
  • the Staticcheck documentation for more details about Staticcheck itself.

As a next step you might like to consider:

  • Developer tools as module dependencies
  • Working with private modules
  • Installing Go

assignment to nil map (staticcheck)

Congratulations!

Great work! you are getting closer and closer to archieving your goals. Go foward!

Share your archievements

staticcheck

This package is not in the latest version of its module.

Documentation ¶

Package staticcheck contains analyzes that find bugs and performance issues. Barring the rare false positive, any code flagged by these analyzes needs to be fixed.

  • func CanBinaryMarshal(pass *analysis.Pass, v Value) bool
  • func CheckAddressIsNil(pass *analysis.Pass) (interface{}, error)
  • func CheckAllocationNilCheck(pass *analysis.Pass) (interface{}, error)
  • func CheckArgOverwritten(pass *analysis.Pass) (interface{}, error)
  • func CheckBadRemoveAll(pass *analysis.Pass) (interface{}, error)
  • func CheckBenchmarkN(pass *analysis.Pass) (interface{}, error)
  • func CheckBuiltinZeroComparison(pass *analysis.Pass) (interface{}, error)
  • func CheckCanonicalHeaderKey(pass *analysis.Pass) (interface{}, error)
  • func CheckConcurrentTesting(pass *analysis.Pass) (interface{}, error)
  • func CheckCyclicFinalizer(pass *analysis.Pass) (interface{}, error)
  • func CheckDeferInInfiniteLoop(pass *analysis.Pass) (interface{}, error)
  • func CheckDeferLock(pass *analysis.Pass) (interface{}, error)
  • func CheckDeprecated(pass *analysis.Pass) (interface{}, error)
  • func CheckDoubleNegation(pass *analysis.Pass) (interface{}, error)
  • func CheckDubiousDeferInChannelRangeLoop(pass *analysis.Pass) (interface{}, error)
  • func CheckDuplicateBuildConstraints(pass *analysis.Pass) (interface{}, error)
  • func CheckEarlyDefer(pass *analysis.Pass) (interface{}, error)
  • func CheckEmptyBranch(pass *analysis.Pass) (interface{}, error)
  • func CheckEmptyCriticalSection(pass *analysis.Pass) (interface{}, error)
  • func CheckEvenSliceLength(pass *analysis.Pass) (interface{}, error)
  • func CheckExec(pass *analysis.Pass) (interface{}, error)
  • func CheckExtremeComparison(pass *analysis.Pass) (interface{}, error)
  • func CheckImpossibleTypeAssertion(pass *analysis.Pass) (interface{}, error)
  • func CheckIneffectiveAppend(pass *analysis.Pass) (interface{}, error)
  • func CheckIneffectiveCopy(pass *analysis.Pass) (interface{}, error)
  • func CheckIneffectiveFieldAssignments(pass *analysis.Pass) (interface{}, error)
  • func CheckIneffectiveLoop(pass *analysis.Pass) (interface{}, error)
  • func CheckIneffectiveRandInt(pass *analysis.Pass) (interface{}, error)
  • func CheckIneffectiveSort(pass *analysis.Pass) (interface{}, error)
  • func CheckIneffectiveURLQueryModification(pass *analysis.Pass) (interface{}, error)
  • func CheckInfiniteEmptyLoop(pass *analysis.Pass) (interface{}, error)
  • func CheckInfiniteRecursion(pass *analysis.Pass) (interface{}, error)
  • func CheckIntegerDivisionEqualsZero(pass *analysis.Pass) (interface{}, error)
  • func CheckLeakyTimeTick(pass *analysis.Pass) (interface{}, error)
  • func CheckLhsRhsIdentical(pass *analysis.Pass) (interface{}, error)
  • func CheckLoopCondition(pass *analysis.Pass) (interface{}, error)
  • func CheckLoopEmptyDefault(pass *analysis.Pass) (interface{}, error)
  • func CheckMapBytesKey(pass *analysis.Pass) (interface{}, error)
  • func CheckMaybeNil(pass *analysis.Pass) (interface{}, error)
  • func CheckMissingEnumTypesInDeclaration(pass *analysis.Pass) (interface{}, error)
  • func CheckModuloOne(pass *analysis.Pass) (interface{}, error)
  • func CheckNaNComparison(pass *analysis.Pass) (interface{}, error)
  • func CheckNegativeZeroFloat(pass *analysis.Pass) (interface{}, error)
  • func CheckNilContext(pass *analysis.Pass) (interface{}, error)
  • func CheckNilMaps(pass *analysis.Pass) (interface{}, error)
  • func CheckNonOctalFileMode(pass *analysis.Pass) (interface{}, error)
  • func CheckPredeterminedBooleanExprs(pass *analysis.Pass) (interface{}, error)
  • func CheckRangeStringRunes(pass *analysis.Pass) (interface{}, error)
  • func CheckRepeatedIfElse(pass *analysis.Pass) (interface{}, error)
  • func CheckScopedBreak(pass *analysis.Pass) (interface{}, error)
  • func CheckSeeker(pass *analysis.Pass) (interface{}, error)
  • func CheckSelfAssignment(pass *analysis.Pass) (interface{}, error)
  • func CheckSideEffectFreeCalls(pass *analysis.Pass) (interface{}, error)
  • func CheckSillyBitwiseOps(pass *analysis.Pass) (interface{}, error)
  • func CheckSillyRegexp(pass *analysis.Pass) (interface{}, error)
  • func CheckSingleArgAppend(pass *analysis.Pass) (interface{}, error)
  • func CheckStaticBitShift(pass *analysis.Pass) (interface{}, error)
  • func CheckStructTags(pass *analysis.Pass) (interface{}, error)
  • func CheckTemplate(pass *analysis.Pass) (interface{}, error)
  • func CheckTestMainExit(pass *analysis.Pass) (interface{}, error)
  • func CheckTimeSleepConstant(pass *analysis.Pass) (interface{}, error)
  • func CheckTimerResetReturnValue(pass *analysis.Pass) (interface{}, error)
  • func CheckToLowerToUpperComparison(pass *analysis.Pass) (interface{}, error)
  • func CheckTypeAssertionShadowingElse(pass *analysis.Pass) (interface{}, error)
  • func CheckTypedNilInterface(pass *analysis.Pass) (interface{}, error)
  • func CheckUnreachableTypeCases(pass *analysis.Pass) (interface{}, error)
  • func CheckUnreadVariableValues(pass *analysis.Pass) (interface{}, error)
  • func CheckUnsafePrintf(pass *analysis.Pass) (interface{}, error)
  • func CheckUntrappableSignal(pass *analysis.Pass) (interface{}, error)
  • func CheckWaitgroupAdd(pass *analysis.Pass) (interface{}, error)
  • func CheckWriterBufferModified(pass *analysis.Pass) (interface{}, error)
  • func ConvertedFrom(v Value, typ string) bool
  • func ConvertedFromInt(v Value) bool
  • func InvalidUTF8(v Value) bool
  • func Pointer(v Value) bool
  • func UnbufferedChannel(v Value) bool
  • func UniqueStringCutset(v Value) bool
  • func ValidHostPort(v Value) bool
  • func ValidateRegexp(v Value) error
  • func ValidateTimeLayout(v Value) error
  • func ValidateURL(v Value) error
  • type Argument
  • func (arg *Argument) Invalid(msg string)
  • func (c *Call) Invalid(msg string)
  • type CallCheck
  • func RepeatZeroTimes(name string, arg int) CallCheck

Constants ¶

Variables ¶, functions ¶, func canbinarymarshal ¶, func checkaddressisnil ¶, func checkallocationnilcheck ¶ added in v0.3.0, func checkargoverwritten ¶, func checkbadremoveall ¶ added in v0.3.0, func checkbenchmarkn ¶, func checkbuiltinzerocomparison ¶ added in v0.2.0, func checkcanonicalheaderkey ¶, func checkconcurrenttesting ¶, func checkcyclicfinalizer ¶, func checkdeferininfiniteloop ¶, func checkdeferlock ¶, func checkdeprecated ¶, func checkdoublenegation ¶, func checkdubiousdeferinchannelrangeloop ¶, func checkduplicatebuildconstraints ¶, func checkearlydefer ¶, func checkemptybranch ¶, func checkemptycriticalsection ¶, func checkevenslicelength ¶, func checkexec ¶, func checkextremecomparison ¶, func checkimpossibletypeassertion ¶, func checkineffectiveappend ¶, func checkineffectivecopy ¶, func checkineffectivefieldassignments ¶ added in v0.2.0, func checkineffectiveloop ¶, func checkineffectiverandint ¶ added in v0.3.0, func checkineffectivesort ¶ added in v0.3.0, func checkineffectiveurlquerymodification ¶ added in v0.2.0, func checkinfiniteemptyloop ¶, func checkinfiniterecursion ¶, func checkintegerdivisionequalszero ¶ added in v0.2.0, func checkleakytimetick ¶, func checklhsrhsidentical ¶, func checkloopcondition ¶, func checkloopemptydefault ¶, func checkmapbyteskey ¶, func checkmaybenil ¶, func checkmissingenumtypesindeclaration ¶, func checkmoduloone ¶ added in v0.3.0, func checknancomparison ¶, func checknegativezerofloat ¶ added in v0.2.0, func checknilcontext ¶, func checknilmaps ¶, func checknonoctalfilemode ¶, func checkpredeterminedbooleanexprs ¶, func checkrangestringrunes ¶, func checkrepeatedifelse ¶, func checkscopedbreak ¶, func checkseeker ¶, func checkselfassignment ¶, func checksideeffectfreecalls ¶ added in v0.4.0, func checksillybitwiseops ¶, func checksillyregexp ¶, func checksingleargappend ¶, func checkstaticbitshift ¶, func checkstructtags ¶, func checktemplate ¶, func checktestmainexit ¶, func checktimesleepconstant ¶, func checktimerresetreturnvalue ¶, func checktolowertouppercomparison ¶, func checktypeassertionshadowingelse ¶ added in v0.3.0, func checktypednilinterface ¶, func checkunreachabletypecases ¶, func checkunreadvariablevalues ¶, func checkunsafeprintf ¶, func checkuntrappablesignal ¶, func checkwaitgroupadd ¶, func checkwriterbuffermodified ¶, func convertedfrom ¶.

ConvertedFrom reports whether value v was converted from type typ.

func ConvertedFromInt ¶

Func invalidutf8 ¶, func pointer ¶, func unbufferedchannel ¶, func uniquestringcutset ¶, func validhostport ¶, func validateregexp ¶, func validatetimelayout ¶, func validateurl ¶, type argument ¶, func (*argument) invalid ¶, type call ¶, func (*call) invalid ¶, type callcheck ¶, func repeatzerotimes ¶, type value ¶, source files ¶.

  • analysis.go
  • buildtag.go
  • structtag.go

Directories ¶

Keyboard shortcuts.

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

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

@believening

believening commented Jan 5, 2023

The text was updated successfully, but these errors were encountered:

@YonkaFang

Successfully merging a pull request may close this issue.

@believening

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

assignment to nil map (staticcheck)

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

assignment to nil map (staticcheck)

Documentation

Twitter Logo

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

IMAGES

  1. 【Golang】Assignment to entry in nil map

    assignment to nil map (staticcheck)

  2. [Solved] Runtime error: assignment to entry in nil map

    assignment to nil map (staticcheck)

  3. 27 Assignment To Entry In Nil Map

    assignment to nil map (staticcheck)

  4. Assignment To Entry In Nil Map

    assignment to nil map (staticcheck)

  5. Assignment To Entry In Nil Map

    assignment to nil map (staticcheck)

  6. Assignment to entry in nil map in golang

    assignment to nil map (staticcheck)

VIDEO

  1. Best way to get the flag in Castles map Narrow One

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

  3. WARZONE 2: SEASON 5 RELOADED (The 🌀🌀🌀 Has Passed)

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

  5. RoWar Team Battle. Space Cruise Secrets/Glitches

  6. ONLY 0,0001% CAN WIN This map😱 only flying don't touch floor👀🤯

COMMENTS

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

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

  3. Runtime error: "assignment to entry in nil map"

    mapassign1: runtime·panicstring("assignment to entry in nil map"); I attempt to make an array of Maps, with each Map containing two indicies, a "Id" and a "Investor". My code looks like this:

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

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

  6. github.com/vcabbage/go-staticcheck

    Staticcheck is go vet on steroids, applying a ton of static analysis checks you might be used to from tools like ReSharper for C#. ... For example, to ignore assignment to nil maps in all test files in the os/exec package, you would write -ignore "os/exec/*_test.go:SA5000" Additionally, the check IDs support globbing, too. ...

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

    golang中map是引用类型,应用类型的变量未初始化时默认的zero value是nil。直接向nil map写入键值数据会导致运行时错误 panic: assignment to entry in nil map 看一个例子: package main const alphabetStr string = "abcdefghijklmnopqrstuvwxyz" func main() { var alphabetMap map[string]bool for _, r := ran

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

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

  10. How to use and tweak Staticcheck

    By Dominik Honnef, author of Staticcheck.. Staticcheck is a state of the art linter for the Go programming language. Using static analysis, it finds bugs and performance issues, offers simplifications, and enforces style rules.. Its checks have been designed to be fast, precise and useful. When Staticcheck flags code, you can be sure that it isn't wasting your time with unactionable warnings.

  11. github.com/gm42/go-tools/cmd/staticcheck

    staticcheck. staticcheck is go vet on steroids, applying a ton of static analysis checks you might be used to from tools like ReSharper for C#. ... For example, to ignore assignment to nil maps in all test files in the os/exec package, you would write -ignore "os/exec/*_test.go:SA5000" Additionally, the check IDs support globbing, too. ...

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

    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.

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

  15. Getting started

    Running Staticcheck. The staticcheck command works much like go build or go vet do. It supports all of the same package patterns. For example, staticcheck . will check the current package, and staticcheck ./... will check all packages. For more details on specifying packages to check, see go help packages.. Therefore, to start using Staticcheck, just run it on your code: staticcheck ./....

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

    plugin: assignment to nil map (SA5000)go-staticcheck #265. Closed believening opened this issue Jan 5, 2023 · 0 comments · Fixed by #268. Closed plugin: assignment to nil map (SA5000)go-staticcheck #265. believening opened this issue Jan 5, 2023 · 0 comments · Fixed by #268. Comments.

  17. go

    var m map[string]string your m variable is assigned with a default value of map, which is nil, not an empty map. This is why you get that error, you are trying to add a value to a nil map. To initialize an empty map, you can try any of these: var m map[string]string = map[string]string{} m := make(map[string]string) m := map[string]string{}

  18. Checks

    Non-canonical key in http.Header map: SA1010 (*regexp.Regexp).FindAll called with n == 0, which will always return zero results: 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

  19. panic: assignment to entry in nil map on single simple map

    Oh it can, that's why I wrote var neighbours = make(map[COO][]COO), you can put that instead of var neighbours map[COO][]COO. The confusion stems probably from the fact that a nil slice is valid to use for normal slice operations, but a nil map isn't valid to use for map operations. -

  20. assignment to nil map golang

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

  21. go

    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.