Code Inspections in Go
Last modified: 12 December 2022This topic lists all GoLand code inspections available in Go.
You can toggle specific inspections or change their severity level on the Editor | Inspections page of the IDE settings Ctrl+Alt+S.
Probable bugs
Inspection | Description | Default Severity |
---|---|---|
'FailNow' in a non-test goroutine | Reports calls to FailNow call runtime.Goexit and stop the calling goroutine, not the test. Therefore, they must only be called from the goroutine that runs the test or benchmark. For more information about FailNow , see func (*T) FailNow at golang.org. Example:
| |
'Unmarshal' is called with the incorrect argument | Reports calls to Unmarshal , see func Unmarshal at golang.org. Example:
| |
'context.CancelFunc' is not called | Reports execution paths that do not call the WithCancel , WithDeadline , and WithTimeout functions take a Context (the parent) and return a derived Context (the child) and a CancelFunc . Calling the CancelFunc cancels the child and its children, removes the parent's reference to the child, and stops any associated timers. Failing to call the CancelFunc leaks the child and its children until the parent is canceled or the timer fires. For more information about the context package, see Package context at golang.org. Example:
| |
Defer/go statement calls 'recover' or 'panic' directly | Reports panic() and recover() mechanism. In particular:
| |
Division by zero | Reports division by zero. Division by zero will lead to a runtime panic. Example:
| |
Exceeded shift expression | Reports shift expressions that equal or exceed the width of the integer. All the bits of the left operand are shifted in such expression resulting in a constant value. The constant value indicates that either the shift offset is incorrect or the shift expression is redundant. Example:
| |
Imported package name as a name identifier | Reports declarations of variables, arguments or functions that overlap with the used import. While legal, such declarations will make using the package exported identifiers impossible after the declaration or create confusion when reading the code. Example:
fmt and iio clash with names of import packages. Not to confuse them later in code, it is better to rename these variables. | |
Impossible interface type assertion | Reports impossible interface-to-interface type assertions. Checks for type assertionsv.(T) and corresponding type-switch cases in which the static type V of v is the interface that cannot possibly implement the target interface T . This occurs when V and T contain methods with the same name but different signatures. Example:
Read method in v has a different signature than the Read method in io.Reader , so this assertion cannot succeed. This inspection only reports if the language version is 1.15 or higher. | |
Incorrect 'strings.Replace' count argument | Reports 0 as it will not replace anything and make the function call redundant. Use -1 instead. Example:
| |
Incorrect usage of 'fmt.Printf' and 'fmt.Println' functions | Reports incorrect usages of %s , %d , %v , and others. If formatting verbs are used incorrectly, the result of a formatting function will contain an error. For more information about formatting verbs, see Package fmt at golang.org. Example:
id: %!s(int=42) . It might be not what you really want. The following function uses the %d formatting verb. The output with the %d formatting verb will be id: 42 .
| |
Incorrect usage of the 'errors.As' function | Reports calls of the As function, see func As at golang.org. Example:
| |
Incorrect usage of the 'sync/atomic' package | Reports assignment statements of the form sync/atomic API. To make them atomic, one need to remove the assignment to use a direct call: atomic.AddUint64(&x, 1) . In that case, the value of x will be updated atomically by address. Example:
| |
Integer to string type conversion | Reports conversions of x , and not a decimal string representation of x as one might expect. Furthermore, if x denotes an invalid code point, the conversion cannot be statically rejected. For conversions that intend on using the code point, consider replacing them with string(rune(x)) . Otherwise, strconv.Itoa and its equivalents return the string representation of the value in the desired base. Example:
| |
Invalid conversions of 'uintptr' to 'unsafe.Pointer' | Reports possibly incorrect conversions of uintptr to unsafe.Pointer is invalid if it implies that there is a uintptr -typed word in memory that holds a pointer value, because that word will be invisible to stack copying and to the garbage collector. Example of invalid usage:
| |
Locks mistakenly passed by value | Reports locks that are mistakenly passed by values. Accidentally copying a value containing a lock may cause both copies to work incorrectly. Generally, such values should be referred to through a pointer. A lock here means a type implementingsync.Locker , such as sync.Mutex or sync.WaitGroup . Example:
| |
Loop variables captured by the func literal | Reports references to loop variables from within
defer and go statements when they are the last statement in the loop body. Otherwise, the analysis might produce false detections. | |
Malformed build tag | Reports malformed build tags and build tags in the incorrect location. The
// +build ignore part should be before the package declaration. To fix that, you can apply the Place build tag before package quick-fix. After the quick-fix is applied:
| |
Malformed struct tag | Reports struct tags that do not conform to Go conventions for struct tags. According to these conventions, tag strings are a concatenation of optionally space-separatedkey:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' ') , quote (U+0022 '"') , and colon (U+003A ':') . Each value is quoted using U+0022 '"' characters and Go string literal syntax. Also, the inspection checks that fields with tags are exported. Example of a valid tag:
| |
Non-standard signature for well-known function names | Reports methods with certain names in the following cases:
io.ByteReader but the signature is wrong. More correct version will be as follows:
| |
Reserved word used as name | Reports declarations of variables, arguments or functions that overlap with the built-in or reserved keyword. If you receive this error then your code might not be as explicit as possible and might confuse other users. Example:
byte and string collide with the built-in type aliases. Therefore, they will be highlighted. consider renaming such declarations. | |
Shadowing variable | Reports declarations of variables that overlap with the declarations in the outer scope. As the meaning of the variable depends on the scope in that case, it may create confusion and lead to unintended consequences. Example:
i variable in the embedded loop is shadowed. To get rid of shadowing, consider renaming the variable in the embedded loop.
| |
Unhandled error | Reports calls to functions and methods that do not handle the call result of the
| |
Unused function or method call result | Reports calls to certain functions and methods that do not handle a call result. An API of such functions imply that users should call them mostly to get a return value and process it, not for side effects. Calls that do not handle the result could be an indication of a misuse of the API. Example:
| |
Control flow issues
Inspection | Description | Default Severity |
---|---|---|
'defer' in the loop | Reports defer in loops can lead to resource leaks or unpredictable execution order of statements. Example:
defer row.Close() inside the loop are not executed until the function completes its execution. Not at the end of each step of the for loop. Such implementation might lead to overflow of the function's stack and other issues. | |
Assignment to a receiver | Reports assignments to method receivers. When you assign a value to the method receiver, the value will not be reflected outside of the method itself. Values will be reflected in subsequent calls from the same method. Example:
| |
Infinite 'for' loop | Reports empty
| |
Unreachable code | Reports code that can never be executed because there exists no control flow path to the code from the rest of the program. Example:
| |
Code style issues
Inspection | Description | Default Severity |
---|---|---|
Comment has no leading space | Reports comments without a leading space. Note that the inspection works only if you select the Add a leading space to comments in Editor | Code Style | Go on the Other tab. Comments with a leading space can be easier to read since the first word is separated from the comment by a space. Example:
| |
Comment of exported element starts with the incorrect name | Reports comments that do not start with the name of the exported element. According to Comment Sentences at golang.org, this is a convention to begin a comment with the name of the exported element. Example:
| |
Error string should not be capitalized or end with punctuation | Reports format issues in error strings. Example:
| |
Exported element should have a comment | Reports exported declarations without a documentation comment. According to Doc Comments at golang.org, all top-level exported names should have doc comments. Also, for more information about comment sentences, see Comment Sentences at golang.org. | |
Exported element should have its own declaration | Reports exported variables or constants in comma-separated lists of declarations. Example:
| |
Name starts with a package name | Reports exported names that start with a package name. This inspection does not report such names in the
MyPackageGetIP name will be highlighted as it starts with the package name. According to Package Names at golang.org, all references to names in a package will be done using the package name, so one can omit that name from the identifiers. For example, if you are in a package foo , you do not need a type FooFile , which clients will write as foo.FooFile . Instead, we name the type File , which clients will write as foo.File . | |
Receiver has a generic name | Reports receiver names like
| |
Struct initialization without field names | Reports structures that are initialized without specifying their field names. By default, the inspection is available only when you use the type that is defined in a different package. When initializing a structure, it is better to explicitly state field names in order to ensure that in case of changes in order of these fields or in names of the fields, they will correctly continue to be addressed. Example:
LimitedReader initialization will be highlighted because explicit names for struct fields are missing. You can apply the Add keys and delete zero values quick-fix to the struct initialization. After the quick-fix is applied, the code looks as follows:
| |
Unit-specific suffix for 'time.Duration' | Reports unit-specific suffixes in constant and variable names of go lint . A list of suffixes that imply a time unit is available in the golang repository at github.com. time.Duration represents a value in nanoseconds, so adding a time unit suffix might make the meaning of the variable confusing, or even indicate a misuse of the time.Duration API. Example:
| |
Unsorted imports | Reports unsorted imports. All Go programs should be formatted in the same way, the formatting rules are fixed by the gofmt tool. Those rules require imports to be sorted. Example of a wrong sorting:
| |
Usage of Snake_Case | Reports usage of snake case instead of camelcase for naming variables, constants and functions. According to MixedCaps at golang.org, camelcase is a convention in Go. Example:
get_external_IP is in snake case but should be in camelcase. You can apply a quick-fix to convert the function name to getExternalIp . | |
General
Inspection | Description | Default Severity |
---|---|---|
Deprecated element | Reports usages of deprecated elements. Example:
SEEK_SET , SEEK_CUR , and SEEK_END are deprecated. | |
Disabled GOPATH indexing | Reports disabled GOPATH indexing that might prevent proper resolution of code references. GOPATH stores your code base and all the files that are necessary for your development. Also, it includes packages that you download and install. If you disabled GOPATH indexing, only project and vendored packages are indexed. It might improve the overall performance but makes it impossible to use packages from GOPATH. | |
Malformed test function name | Reports malformed names of tests, benchmarks, and examples. According to Package testing at golang.org, names must follow a special convention in order to make the go tool process them correctly. Example:
| |
Missing trailing comma before a newline in a composite literal | Reports a missing trailing comma before a newline in composite literals, function call arguments, and function parameter lists. Example:
| |
Redundant parentheses | Reports redundant parentheses in expressions and types. Example:
| |
Unexported return type of the exported function | Reports exported functions with unexported return types. Unexported types can be difficult to use when viewing documentation under go doc. Example:
| |
Unnecessarily exported identifier | Reports exported identifiers that are used only in the package where they are defined but are not used in other packages. Making them exported is redundant and may clutter the API of the package. |
Declaration redundancy
Inspection | Description | Default Severity |
---|---|---|
Bool condition | Reports parts of boolean expressions that are either always
x > 0 && x > 0 part. After the quick-fix is applied, the expression looks as follows: x > 0 . | |
Empty declaration | Reports empty declarations. Empty declarations have no effect. If you remove them, you might improve code readability. Example:
| |
Empty slice declared using a literal | Reports slice declarations with empty literal initializers used instead of nil or an empty slice literal. The first approach is preferred as it does not lead to memory allocation. For more information about empty slices, see Declaring Empty Slices at golang.org. Example:
| |
Redundant blank argument in range | Reports optional blank variables in range loops. When you use therange loop to iterate over a slice, two values are returned for each iteration. The first is the index number, and the second is a copy of the element at that index. If you do not need the second value, you can skip this element instead of using a blank identifier. Example:
| |
Redundant comma | Reports commas that may be omitted in the end of argument lists and composite literals. The IDE suggests removing commas that are considered optional. Removing these commas might improve code readability. Example:
| |
Redundant import alias | Reports aliases of imported packages that may be omitted. Usually, such aliases equal to the names of the imported packages, so aliases have no effect and one can use package names directly. Example:
fmt alias duplicates the package name that is also named "fmt" . To delete the alias, use the Delete import alias quick-fix. After the quick-fix is applied:
| |
Redundant second index in slices | Reports a redundant second index (a high bound) in slice expressions. Usually, the second index is optional. If you remove it, you might improve code readability. Example:
| |
Redundant semicolon | Reports redundant semicolons. Idiomatic Go programs have semicolons only in places such as
| |
Redundant type conversion | Reports type conversions that may be omitted. Example:
"hello" value is the string type already, the additional conversion to string is redundant. To remove the conversion, consider using the Delete conversion quick-fix. After the quick-fix is applied:
| |
Redundant types in composite literals | Reports redundant type declarations in composite literals. Example:
int type. In this case, you can use a shorter definition. You can fix this code manually or use the Delete redundant type quick-fix. After the quick-fix is applied, the code looks as follows:
| |
Self assignment | Reports expressions that are assigned to themselves. Such assignments have no effect, removing them might improve code readability. Example:
| |
Type can be omitted | Reports types in variable and constant declarations that can be omitted since they can be inferred by the compiler. Such types are redundant, omitting them may improve readability of the code. Example:
string type in the variable declaration may be omitted. To remove the type, use the Delete type quick-fix. After the quick-fix is applied:
| |
Unused constant | Reports constants that are defined but are never used in code.
| |
Unused exported function | Reports unused exported functions. In Go, a function is exported if it begins with a capital letter. Names of exported functions that were defined but never used are grayed out.
| |
Unused exported type | Reports unused exported types in the
User struct type is declared but never used in the code. This type will be grayed out. | |
Unused function | Reports unused unexported functions. In Go, a function is unexported if it begins with a small letter. Names of unexported functions that were defined but never used are grayed out.
| |
Unused global variable | Reports global variables that are defined but are never used in code. If you have unused variables, the code will not compile. For more information about unused variables and imports, see Unused imports and variables at golang.org.
| |
Unused parameter | Reports unused function parameters.
42 and bird as arguments. The printAll function accepts two parameters int and string but uses only the first of them. Therefore, the s string is grayed out. | |
Unused type | Reports unused types.
user type will be grayed out because it is not used anywhere in code. | |
Thanks for your feedback!