Golang lint - Different methods with Best Practices

Tuan Nguyen

September 29, 2022

Linting Go Code

In this article, I will demonstrate how to use lint tools in Golang. A linter is a tool that checks code files using a set of rules that describe problems that cause confusion, produce unexpected results, or reduce the readability of the code. Furthermore, lint can help us find potential bugs in the code, such as assigning undeclared variables, which can cause runtime errors, or getting the value from a global variable, which makes debugging difficult, and so on.

Some go packages which can be used to perform linting such as:

  • go vet detects suspicious constructs that the compile may skip, but it only catches a limited number of potential issues such as calling fmt.Printf with the wrong arguments.
  • errcheck , An error checker
  • golangCI-lint ,  It’s a linting tool that provides a facade on top of many useful linters and formatters. Also, it allows running the linters in parallel to improve analysis speed, which is quite handy.

We can also use golint which is maintained by the Go developers. It is intended to enforce the coding conventions described in Effective Go . But for now, this project is frozen and deprecated . You can refer to ' freeze and deprecate golint thread ' to read more.

Besides linters, we should also use code formatters to fix code style. Here is a list of some code formatters for you to try:

  • gofmt package, which is already present in the installation, so we can run it to automatically indent and format your code. Note that it uses tabs for indentation and blanks for alignment
  • goimports , A standard Go imports formatter

Using Golang Vet for linting

go vet : Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string. Vet uses heuristics that do not guarantee all reports are genuine problems, but it can find errors not caught by the compilers.

Let's look at this below example to understand how Golang Vet works:

When we run 'go run main.go', the output will be:

When we run "go vet main.go", the output will be:

Using gofmt to for formatting

The gofmt formatting don’t affect the execution of the code—rather, they improve codebase readability by ensuring that the code is visually consistent. gofmt focuses on things like indentation, whitespace, comments, and general code succinctness. We have written a dedicate chapter on go formatting .

To check files for unnecessary parentheses:

To remove the parentheses:

Consider the below example to see how gofmt format the code:

The program will automatically format to this:

Using GolangCI-Lint to lint go program

Golangci-lint is a Go linters tool that runs linters in parallel, reuses the Go build cache, and caches analysis results for significantly improved performance on subsequent runs, is the preferred way to configure linting in Go projects

For convenience and performance reasons, the golangci-lint project was created to aggregate and run several individual linters in parallel. When you install the program, it will include about 48 linters (at the time of writing), and you can then choose which ones are important for your project.

Set up environment

To install golangci-lint , run the command below:

To see a list of supported linters and which linters are enabled/disabled:

Golang lint - Different methods with Best Practices

Perform Test Run

You may encounter errors if you run the enabled linters from the root of your project directory. Each problem is reported with all of the context you need to fix it, including a brief description of the problem as well as the file and line number where it occurred.

Golang lint - Different methods with Best Practices

By passing the path, you can specify which directories and files to analyze.

Configuring GolangCI-Lint

The config file has lower priority than command-line options. If the same bool/string/int option is provided on the command-line and in the config file, the option from command-line will be used. Slice options (e.g. list of enabled/disabled linters) are combined from the command-line and config file.

Config File

GolangCI-Lint looks for config files in the following paths from the current working directory:

  • .golangci.yml
  • .golangci.yaml
  • .golangci.toml
  • .golangci.json

Example of  .golangci.yaml config file:

Command-Line Options

Pass -E/--enable to enable linter and -D/--disable to disable:

Suppressing linting errors

Disabling specific linting issues that arise in a file or package is sometimes necessary. This can be accomplished in two ways: via the nolint directive and via exclusion rules in the configuration file.

The nolint  directive

Here is an example of generating a random number:

When we run golangci-lint run -E gosec lint.go  the output will be:

The linter recommends using the Int method from crypto/rand instead because it is more cryptographically secure, but it has a less friendly API and slower performance. You can ignore the error by adding a nolint directive to the relevant line:

This inline use of nolint disables all linting issues detected for that line. You can disable issues from a specific linter by naming it in the directive (recommended).

When a nolint directive is used at the top of a file, it disables all linting issues for that file:

Exclusion rules

Exclude Issue by Text : Exclude issue by text using command-line option -e or config option issues.exclude . It's helpful when you decided to ignore all issues of this type. Also, you can use issues.exclude-rules config option for per-path or per-linter configuration.

Exclude Issues by Path:

Exclude issues in path by run.skip-dirs , run.skip-files or issues.exclude-rules config options. In the following example, all the reports from the linters (linters) that concerns the path (path) are excluded:

The code checking tools mentioned above are mostly the "official" ones (the ones maintained by Golang developers). IDE integrations are a nice benefit of having official tooling. For example, Goland includes gofmt support, and VSCode includes an official Go extension that can check your code whenever you save a file.

There are plenty of great options for keeping your code clean and consistent, whether you use these official code checkers or others provided by the community. This article should have given you a better understanding of how to use go vet , gofmt to benefit your code.

https://pkg.go.dev/cmd/vet https://github.com/golangci/golangci-lint https://pkg.go.dev/cmd/gofmt https://pkg.go.dev/golang.org/x/lint/golint https://go.dev/doc/effective_go

He is proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise spanning these technologies, he develops robust solutions and implements efficient data processing and management strategies across various projects and platforms. You can connect with him on LinkedIn .

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to [email protected]

Thank You for your support!!

Leave a Comment Cancel reply

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

Notify me via e-mail if anyone answers my comment.

ineffectual assignment to golang lint

We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Programming Languages

Exam certifications.

Certified Kubernetes Application Developer (CKAD)

CompTIA PenTest+ (PT0-002)

Red Hat EX407 (Ansible)

Hacker Rank Python

Privacy Policy

HTML Sitemap

Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

Linting Go programs: A guide to improving code quality

ineffectual assignment to golang lint

Using linters improves readability by highlighting problems before they are executed, and it helps with the standardization of your codebase. A good linter has configuration settings that help to lessen warnings for rules you don’t care about, making code easier to comprehend, modify, and maintain.

Go Logo

In this article, we’ll be learning more about linting through these topics:

Setting up a project with revive

Suppressing linting errors with revive, setting up configurations for linters, setting up linting in code editors, exploring the go vet command, alternative packages for linting in go.

golint has been the most widely used linter for Go over the years. Unfortunately, it is now officially deprecated and archived. The issue with golint is that it doesn’t offer any configuration options and always applies all the rules, which leads to warnings for rules you don’t care about. In this article, we’ll use the revive package as well as exploring alternative go linting packages.

Conversely, revive is a fast, configurable, extensible, adaptable, and beautiful linter for Go. It serves as golint’s drop-in replacement.

Here’s how revive is different from golint:

  • Allows us to enable or disable rules using a configuration file
  • Allows us to configure the linting rules with a TOML file
  • Is two times faster running the same rules as golint
  • Provides functionality for disabling a specific rule or the entire linter for a file or a range of lines (golint allows this only for generated files)
  • Optional type checking. Most rules in golint do not require type checking. If you disable them in the config file, revive will run over six times faster than golint
  • Provides multiple formatters that let us customize the output
  • Allows us to customize the return code for the entire linter or based on the failure of only some rules
  • Everyone can extend it easily with custom rules or formatters
  • revive provides more rules compared to golint

Open a terminal and create a project folder. Navigate to the project folder and run the following command to start a new project:

Navigate to your Go project and run the following command to install the revive linter package:

Create a main.go file and add the following code snippet to the main.go file:

Now, run the revive command on the project terminal and you should get the following report:

In Go, the first letter of an exported function is usually an uppercase. A properly documented codebase requires that exported functions be commented with a brief overview of the function’s purpose, so everyone can understand what it does. Now we can see how the revive package helps us write well-documented code.

Now, let’s add some comments to these functions:

Execute the revive command and you should have the following report:

Revive tells us that our comment should begin with the name of our exported functions for a properly documented codebase.

Let’s change our comments to the following:

With this, execute the revive command and you should have no report.

Sometimes, it’s necessary to disable specific linting issues that appear in a file or package. Both comments and exclusion rules in the configuration file can be used to do this. Let’s examine each strategy in turn.

The comments strategy comes in handy when you want to disable warnings for a certain section of code but still want to apply the rule to other parts of the project.

Here is how to disable specific linting issues using comments:

The syntax for this is revive , followed by a colon, then disable . If desired, add another colon followed by the name of a linter rule.

This is one amazing feature of the revive linter package that address the major challenge with the popular golint linter package.

Let’s see how to configure the revive linter package to disable some linting rules in order to reduce unnecessary warnings.

Add a file named revive.toml to the project folder with the default revive configuration :

Now, remove all comments and run the following command to use the linter with the configuration file:

To disable any of these rules, you can either remove them or add # before the specified rule as follows:

Some code editors support linting code automatically; Visual Studio Code is one of them.

ineffectual assignment to golang lint

Over 200k developers use LogRocket to create better digital experiences

ineffectual assignment to golang lint

Let’s see how to set up the revive linter in Visual Studio Code.

Open VS Code and install the go extension for VS Code. Then, select the File tab > Preferences > Settings and add go.lint to the search field and select revive in the Go: Lint Tool section.

Go Lint in Search Field

The default Go linter for Visual Studio Code is staticcheck .

In contrast to linters, the go vet command identifies code that compiles but probably won’t perform as intended.

Let’s consider a common self assignment bug in our Golang code. Update main.go file as follows:

The above code will compile even with this bug. Executing the revive linter command won’t report any issue concerning this bug. This is where the go vet command comes in handy.

Run the go vet command and you should have the following result instead:

If revive isn’t your preference, here is a list of Go linters that have been built and maintained by the community.

golangci-lint

golangci-lint is a fast Go linters runner. It integrates with every major IDE, employs caching, enables YAML configuration, executes linters in parallel, and comes with a large number of linters.

staticcheck

staticcheck is a cutting-edge Go programming language linter. It employs static analysis to identify bugs and performance problems, provide simplifications, and enforce style guidelines.

Go takes documentation seriously because the easier it is for developers to produce good documentation, the better for everyone.

In this article, we’ve explored linting in Golang, my preferred linting package, and alternative packages for linting in Go. I hope you’ll like working with revive!

More great articles from LogRocket:

  • Don't miss a moment with The Replay , a curated newsletter from LogRocket
  • Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
  • Use React's useEffect to optimize your application's performance
  • Switch between multiple versions of Node
  • Discover how to use the React children prop with TypeScript
  • Explore creating a custom mouse cursor with CSS
  • Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

Get set up with LogRocket's modern error tracking in minutes:

  • Visit https://logrocket.com/signup/ to get an app ID

Install LogRocket via npm or script tag. LogRocket.init() must be called client-side, not server-side

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)

ineffectual assignment to golang lint

Stop guessing about your digital experience with LogRocket

Recent posts:.

Comparing Mutative Vs Immer Vs Reducers For Data Handling In React

Comparing React state tools: Mutative vs. Immer vs. reducers

Mutative processes data with better performance than both Immer and native reducers. Let’s compare these data handling options in React.

ineffectual assignment to golang lint

Radix UI adoption guide: Overview, examples, and alternatives

Radix UI is quickly rising in popularity and has become an excellent go-to solution for building modern design systems and websites.

ineffectual assignment to golang lint

Understanding the CSS revert-layer keyword

In this article, we’ll explore CSS cascade layers — and, specifically, the revert-layer keyword — to help you refine your styling strategy.

ineffectual assignment to golang lint

Exploring Nushell, a Rust-powered, cross-platform shell

Nushell is a modern, performant, extensible shell built with Rust. Explore its pros, cons, and how to install and get started with it.

ineffectual assignment to golang lint

Leave a Reply Cancel reply

Two linters I'll always add to new Go projects: errcheck and ineffassign

Jul 17, 2020

The reason for that is that they are the best bang for your buck by far. They are easy to appease, I have yet to see them produce false positives, they very frequently catch outright buggy code and retrofitting them is a pain.

ineffassign

This is the sort of thing that ineffassign prevents:

This is perfectly valid code, and will write garbage sometimes, without any indication whatsoever. Yes, Go does refuse to compile code like this

because data is not used, but declaring a variable and then immediately overwriting its value is perfectly legal and almost never what you want. At best the variable was never needed, in which case a _ is a good way to signal it, or it was meant to be used and ineffassign found a bug.

I’ve seen this pattern frequently enough in tests, where part of the test code accidentally doesn’t check intermediate errors or return values, leading to parts of the test silently breaking over time.

To its credit, gopls does check for this now .

In a similar vein, errcheck enforces checking error return values. In Go, errors are values, and unlike other 1 languages 2 , nothing enforces they are checked.

This is valid:

And so are all these:

The only difference is that the first example carries no indication where this was intentional or not. errcheck enforces that error values are at least assigned to _ , therefore being explicit that a decision was made to ignore the error 3 .

One case where this matters is when writing new code. It’s easy enough to forget about checking all error returns of all functions called. Again, tests passing by accident is a very frequent occasion, and so is production code.

Another also interesting case is functions changing signatures. When adding an error return to a function that previously returned nothing or updating a dependency that does so, you probably want to verify all the call sites, at the very least making the executive choice to explicitly ignore the errors.

Retrofitting using golangci-lint

golangci-lint has positioned itself as the tool everyone uses on CI, and I’d say with good reason. It supports many linters, has improved massively over the past couple of years and has facilities for wiring up into existing codebases by only checking code that changes 4 , allowing for incremental cleanup.

For example:

No one has to fix the unchecked error, until they touch the call in bar() . This works well, until you realise there are transformations where this heuristic falls flat. This is still true according to the latest golangci-lint, 1.28.3.

Here is an example of this in action:

Since the call to foo() is not touched, golangci-lint considers the unchecked error pre-existing and does not report it! The check is completely elided on changes that simply go from zero returns to a single error return. This simply makes the check not as useful as it could be, allowing regressions to merge over time.

The other problem with retrofitting is that the cleanup can be boring and take a long time. Clearing hundreds for errors in bulk is mind-numbing. Merely shifting around existing code might require fixing existing issues, unrelated to the change at hand.

Why go through that, when simply adding these linters from the start does the trick and saves you from bugs?

Addendum - 18th July

I got a bit curious about k8s’ code, and ran ineffassign against it. There is one case where ineffassign could be considered noisy, and that is using foo := true instead of var foo bool :

The code in question:

This nudges towards var exist bool or bool := false . Clearly there is no bug here, the result is the same either way, so it boils down to the style used when declaring variables.

good  ↩

Rust  ↩

Not necessarily a good decision, you can always find yourself staring at git blame wondering why.  ↩

according to git and revgrep, using the new- settings in the config . Nowadays it works, a long time ago I found out the hard way it didn’t   ↩

DEV Community

DEV Community

Guiyomh

Posted on Oct 31, 2023

golangci-lint: a powerful and complete Go linter

golangci-lint is a Go linter tool that helps detect and fix style errors, convention errors, and potential vulnerabilities. It is based on a set of predefined rules, but you can also create your own rules.

Installation and configuration

To run golangci-lint on your project, use the following command:

golangci-lint will display the list of errors and warnings found. You can also use the --format option to display the results in a custom format.

Here are some examples of issues that golangci-lint can detect:

  • Style errors : golangci-lint can detect the most common Go style errors, such as using uninitialized variables, missing comments, and bad indentation.
  • Convention errors : golangci-lint can detect violations of Go coding conventions, such as using non-compliant variable names or missing unit tests.
  • Vulnerabilities : golangci-lint can detect known vulnerabilities in Go code, such as the use of outdated encryption primitives or lack of input validation.

Configuration

golangci-lint is a very configurable tool. It supports several formats YAML, JSON, TOML. You can customize linter rules to meet your specific needs.

Enable or disable linters

This configuration activates all linters except those listed.

Apply specific rules

For example, you can add custom rules to detect issues specific to your project.

This configuration prohibits the use of certain packages (this is an example)

Linter included

Golangci-lint includes over 30 linters, which cover a wide range of code quality issues. These linters are divided into several categories:

  • A variable declared without initialization.
  • A function declared with an inappropriate name.
  • A function that does not return a value.
  • A function that uses an inappropriate data type for a parameter.
  • A function that does not properly isolate errors.
  • A function that uses an uninitialized variable.
  • A loop that could be replaced by an arithmetic expression.
  • A function that could be simplified to improve performance.
  • A function that uses an inefficient Go structure.
  • A variable that is used only once.
  • A function that is too long.
  • A function that is not well documented.

To get a list of supported linters and enabled/disabled linters, you can do the following command:

Integration with IDEs

Golangci-lint offers integrations with major Go IDEs, allowing you to run the linter directly from your IDE.

To install the IDE extension for Visual Studio Code, open the VS Code Marketplace and search for "golangci-lint". Click on the extension to install it and add it to your configuration:

You can adjust golangci-lint's behavior to suit your needs by configuring it. You can make sure your code is of the highest caliber by taking the effort to configure golangci-lint.

The following advice will help you configure golangci-lint:

  • Start with a simple setup and add options as you need them.
  • Learn more about the various configuration choices by reading the golangci-lint manual.
  • Take inspiration from the golangci-lint configuration samples.

I hope this piece clarifies the golangci-lint settings for you.

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

akashpattnaik profile image

The PlayStore Killer

Akash Pattnaik - Feb 27

rizmyabdulla profile image

Check Out My First Node.js Package: Json Flex DB!

Rizmy Abdulla 🎖️ - Mar 29

themuneebh profile image

Rust vs. Go, NO!, It's Rust and Go

Muneeb Hussain - Apr 1

ottok profile image

Communication Is the Key to Efficiency in a Software Engineering Organization

Otto Kekalainen - Mar 31

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Go, Lint. Go! How to Build a Go Linting Rule

S everal months ago, I started working on a Go linter (gomega-lint) for gomega . I’ve been using gomega at work for almost a year and love it now. I’ve formed some opinions on good practices for using gomega. But giving this kind of feedback during code reviews - it’s too late by that point. So, I wanted a Go linter to encourage these good practices.

Creating a new linter or linting rule in Go wasn’t immediately apparent. And I wanted to know how to test the linter. This post shares my lessons learned, and I hope it helps someone else in the future.

Let’s build a contrived rule to prevent invoking fmt.Printf by using singlechecker .

Note: the final code can be found at go-lint-rule-demo

Create a new Go module for the linting rule

We’ll start by creating a new Go project that will have the following structure:

Run the following commands to initialize a new Go module and create the above file structure.

Afterward, you should have the same file structure as above.

Next, let’s download golang.org/x/tools which contains singlechecker .

Build a primitive rule

When I first started to build my rule, I took a naive approach to checking any function call matching “fmt.Printf”. Let’s start by doing that and then talk about the downsides.

I like to try to create failing tests before writing any source code, so let’s make ./internal/rules/nofmtfprintf_test.go with the following content:

This wires up analysistest, a tool used for testing rules. Ultimately, this will run our linting rule within the testdata directory that we’ll now set up with an example code to lint.

Create a new file named internal/rules/testdata/src/nofmtprintf/nofmtprintf.go with the following content:

This file is just a plain ol’ Go file. analysistest will execute our linting rule against this file. analysistest will expect to get a linting error with a message of Don't use fmt.Printf when linting fmt.Printf("hello") . It will also expect zero linting errors on all other lines.

We can execute our unit test via go test ./... .

Let’s now implement our naive rule. Let’s make a new file named ./internal/rules/nofmtprintf.go and populate it with:

A lot happens here if you’re unfamiliar with abstract syntax trees (AST). This code looks for function calls and then checks that the package name is “fmt” and that the function invoked is exactly named “Printf”.

Use types to build a more intelligent rule

So the naive implementation catches “fmt.Printf”. Unfortunately, there are several issues:

  • dot imports of fmt won’t be caught
  • aliasing the fmt import won’t be caught
  • other packages or structs named fmt with a Printf function will be erroneously reported

Let’s update our example code first to prove this:

Our test will start failing as expected. So how do we avoid all of the false negatives and the permutations of aliases?

The parser has a nifty trick - it also identifies types! While analyzing a file, we can also look up information about the package’s imports.

So, what we can do is roughly:

  • Look up the packages imported by the file under inspection
  • Look for the fmt package in the list of imports
  • Lookup the Printf function in fmt package when found

We can get the Printf function’s type once we’ve found the Printf function in the fmt package.

The magic ingredient here is that every usage of fmt.Printf will have the same type. It’ll be the same for any alias and dot import.

Let’s update our rule to look up the “fmt.Printf” function and find matching function calls:

So, not only is our rule more accurate, but it’s simpler!

If you know an even better way, then please let me know!

Compile linter executable

Let’s build a binary so we can use this rule anywhere.

Create a new directory:

and create ./cmd/linter/main.go matching:

Note: there’s also golang.org/x/tools/go/analysis/multichecker if you want to include multiple rules in one binary.

Now we can build our executable with:

and run our executable like:

and we’ll see the same linting errors as our tests!

The singlechecker and multichecker come with great functionality out of the box. You can learn more via ./linter -h . One of the incredible options is the ability to support auto fixes with -fix !

Support auto fixes

Linting is excellent for catching issues, but linters reach another level when they can automatically fix issues. Thankfully, the analysis package supports this as well. Our rule needs to provide suggested fixes for invalid code.

Our example linter rule that is going to replace fmt.Printf arbitrarily with log.Printf .

Let’s start by updating our unit tests:

We’re using RunWithSuggestedFixes instead of Run here. It looks the same as Run , but RunWithSuggestedFixes does the following:

  • Runs the linter to get a report of violations
  • Applies any suggested fixes returned in the report
  • Compares a fixed file to a .golden file

Let’s create ./internal/rules/testdata/src/nofmtfprintf/example.go.golden with the following content:

This file matches the content of our ./internal/rules/testdata/src/nofmtfprintf/example.go file, except the fmt.Printf usages have been replaced with log.Printf .

The TestNoFmtPrintfAutoFix test will start failing now.

One thing to note is the loop over results is only so this test fails from the start. Without this logic, if a rule returns 0 suggested fixes, then RunWithSuggestedFixes doesn’t compare to the .golden file, so the unit test won’t fail.

Now let’s add support for suggested fixes by modifying ./internal/rules/nofmtprintf.go :

Suggested Fixes are a list of text edits to perform on the file. The text edit provides starting and end positions to replace with the new text.

In this case, we always replace it with log.Printf . Once we build the linter, we can use -fix for the suggested fixes to be automatically applied. Also, at this point, our unit test will be passing.

There are a couple of gotchas with this approach to suggested fixes:

  • missing imports aren’t added
  • unused imports aren’t removed

Imagine the file wasn’t importing log . Now we have a compilation issue.

On the flip side, imagine the file only imported fmt for Printf . After all usages of fmt.Printf are replaced with log.Printf , we have an unused import causing another compilation issue.

I am still looking for a reliable way to modify the imports accordingly.

If you know a better way to implement rules or how to handle adding/removing imports, please connect on

Twitter , LinkedIn , or GitHub .

  • Author : Dustin Specker
  • Link : https://dustinspecker.com/posts/build-go-linting-rule/
  • License : CC BY-NC-SA 4.0
  • Go 1.20: Combined Unit and Integration Code Coverage
  • setuid: Elevating Privileges
  • Kubernetes Networking from Scratch: Using BGP and BIRD to Advertise Pod Routes
  • Spin up a Ubuntu VM using Pulumi and libvirt: Component Resources Edition
  • Spin up a Ubuntu VM using Pulumi and libvirt
  • Go 1.20: Combined Unit and Integration Code Coverage >

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

Golint is a linter for Go source code.

Installation

Golint requires a supported release of Go .

Invoke golint with one or more filenames, directories, or packages named by its import path. Golint uses the same import path syntax as the go command and therefore also supports relative import paths like ./... . Additionally the ... wildcard can be used as suffix on relative and absolute file paths to recurse into them.

The output of this tool is a list of suggestions in Vim quickfix format, which is accepted by lots of different editors.

Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes.

Golint differs from govet. Govet is concerned with correctness, whereas golint is concerned with coding style. Golint is in use at Google, and it seeks to match the accepted style of the open source Go project.

The suggestions made by golint are exactly that: suggestions. Golint is not perfect, and has both false positives and false negatives. Do not treat its output as a gold standard. We will not be adding pragmas or other knobs to suppress specific warnings, so do not expect or require code to be completely "lint-free". In short, this tool is not, and will never be, trustworthy enough for its suggestions to be enforced automatically, for example as part of a build process. Golint makes suggestions for many of the mechanically checkable items listed in Effective Go and the CodeReviewComments wiki page .

Golint is meant to carry out the stylistic conventions put forth in Effective Go and CodeReviewComments . Changes that are not aligned with those documents will not be considered.

Contributions

Contributions to this project are welcome provided they are in scope , though please send mail before starting work on anything major. Contributors retain their copyright, so we need you to fill out a short form before we can accept your contribution.

Add this to your ~/.vimrc:

If you have multiple entries in your GOPATH, replace $GOPATH with the right value.

Running :Lint will run golint on the current file and populate the quickfix list.

Optionally, add this to your ~/.vimrc to automatically run golint on :w

Add this to your .emacs file:

Running M-x golint will run golint on the current file.

For more usage, see Compilation-Mode .

Documentation ¶

Package lint contains a linter for Go source code.

  • type Linter
  • func (l *Linter) Lint(filename string, src []byte) ([]Problem, error)
  • func (l *Linter) LintFiles(files map[string][]byte) ([]Problem, error)
  • type Problem
  • func (p *Problem) String() string

Constants ¶

This section is empty.

Variables ¶

Functions ¶, type linter ¶.

A Linter lints Go source code.

func (*Linter) Lint ¶

Lint lints src.

func (*Linter) LintFiles ¶

LintFiles lints a set of files of a single package. The argument is a map of filename to source.

type Problem ¶

Problem represents a problem in some source code.

func (*Problem) String ¶

Source files ¶, directories ¶, keyboard shortcuts.

IMAGES

  1. Golang Tutorial #3

    ineffectual assignment to golang lint

  2. State of Golang linters and the differences between them

    ineffectual assignment to golang lint

  3. The Benefits of Golang Development

    ineffectual assignment to golang lint

  4. What Is Golang?

    ineffectual assignment to golang lint

  5. Golang lint

    ineffectual assignment to golang lint

  6. What is Golang? Advantages and Disadvantage of Go

    ineffectual assignment to golang lint

VIDEO

  1. Golang backend assignment Demo

  2. Ineffectual Loner Explains Chemistry in a Landfill

  3. Map-Reduce Golang Assignment Test Cases Passed

  4. Solving A Subscriber's Golang Interview Assignment!

  5. Go Class: 33 Reflection

  6. Go (Golang) Tutorial #6

COMMENTS

  1. go

    3. Alright, var cfg *utils.Config worked. Thanks. It was needed a declaration only. - Ishmeet. Jun 23, 2021 at 5:25. 1. @Ishmeet, note that the linter wasn't forcing you to use a var declaration; instead it hinted at that you might have a bug in your code—because the first assignment could be way more involved like assigning the return ...

  2. Detect ineffectual assignments in Go code.

    ineffassign. Detect ineffectual assignments in Go code. An assignment is ineffectual if the variable assigned is not thereafter used. This tool misses some cases because it does not consider any type information in its analysis. For example, assignments to struct fields are never marked as ineffectual. It should, however, never give any false ...

  3. Golang lint

    Golang linting is a way to verify the go code to identify any kind of compilation issues, or performance improvements which can be done. ... In this article, I will demonstrate how to use lint tools in Golang. A linter is a tool that checks code files using a set of rules that describe problems that cause confusion, produce unexpected results ...

  4. Linting Go programs: A guide to improving code quality

    $ go vet # sample .\main.go:10:2: self-assignment of name to name Alternative packages for linting in Go. If revive isn't your preference, here is a list of Go linters that have been built and maintained by the community. golangci-lint. golangci-lint is a fast Go linters runner. It integrates with every major IDE, employs caching, enables ...

  5. Two linters I'll always add to new Go projects: errcheck and ineffassign

    Retrofitting using golangci-lint golangci-lint has positioned itself as the tool everyone uses on CI, and I'd say with good reason. It supports many linters, has improved massively over the past couple of years and has facilities for wiring up into existing codebases by only checking code that changes 4 , allowing for incremental cleanup.

  6. "Ineffectual assignment" false positive when var used in deferred

    Running the linter when interacting with a var after passing it to a deferred function call marks it as ineffectual assignment. package main import"errors"funcshutdown ( errerror) { iferr!=nil { panic ( err ) } } funcTestLint () { varerrerrordefershutdown ( err ) iftrue { err=errors.

  7. github.com/gordonklaus/ineffassign

    ineffassign. Detect ineffectual assignments in Go code. An assignment is ineffectual if the variable assigned is not thereafter used. This tool misses some cases because it does not consider any type information in its analysis. For example, assignments to struct fields are never marked as ineffectual. It should, however, never give any false ...

  8. Linting in Go with golangci-lint

    In this workflow, the golangci-lint-action is used to run golangci-lint. It's configured to use version 1.29 of golangci-lint and to run the linter in the connection directory.

  9. golangci-lint: a powerful and complete Go linter

    1 golangci-lint: a powerful and complete Go linter 2 Tame Testing Chaos with Gotestsum. golangci-lint is a Go linter tool that helps detect and fix style errors, convention errors, and potential vulnerabilities. It is based on a set of predefined rules, but you can also create your own rules.

  10. Go, Lint. Go! How to Build a Go Linting Rule

    S everal months ago, I started working on a Go linter (gomega-lint) for gomega.I've been using gomega at work for almost a year and love it now. I've formed some opinions on good practices for using gomega. But giving this kind of feedback during code reviews - it's too late by that point.

  11. ineffassign package

    Package ineffassign implements a static analyzer to ensure that there are no ineffectual assignments in source code. Skip to Main Content . Why Go Case Studies Common problems companies solve with Go. Use Cases Stories about how and why companies use Go. Security Policy How Go can help keep you secure by default ...

  12. x/text: potential Ineffective Assignments in a few packages #35136

    Hi, if it's possible, I would like to work on this. I had run ineffassign on x/text again an found more results. See the the updated list below. Almost all issues can be easily fixed by simply removing or refactoring the ineffectual assignments clauses.

  13. ineffassign command

    Detect ineffectual assignments in Go code. This tool misses some cases because does not consider any type information in its analysis. (For example, assignments to struct fields are never marked as ineffectual.) It should, however, never give any false positives.

  14. Linters

    Detects when assignments to existing variables are not used. unused: v1.0.0: staticcheck It's a set of rules from staticcheck. It's not the same thing as the staticcheck binary. The author of staticcheck doesn't support or approve the use of staticcheck as a library inside golangci-lint. bugs, metalinter: v1.0.0: unused

  15. github.com/golangci/ineffassign

    ineffassign. Detect ineffectual assignments in Go code. This tool misses some cases because does not consider any type information in its analysis. (For example, assignments to struct fields are never marked as ineffectual.) It should, however, never give any false positives.

  16. lint package

    We will not be adding pragmas or other knobs to suppress specific warnings, so do not expect or require code to be completely "lint-free". In short, this tool is not, and will never be, trustworthy enough for its suggestions to be enforced automatically, for example as part of a build process.

  17. Use golangci-lint with lsp-mode

    I've tried using flycheck-golangci-lint but it doesn't seem to be working. I'm testing my config by opening a .go file with an ineffectual assignment that trips golangci-lint when run from the CLI tool. My Go and LSP configs are: :delight lsp-lens-mode "🔍". :ensure t. :init. ;; set prefix for lsp-command-keymap (few alternatives - "C-l", "C ...

  18. static analysis

    Android's syzkaller uses a dedicated build tag to exclude files for golangci-lint.Using that approach prevents parsing of the files, and significantly reduced our memory consumption during build time. At top of the Go files that need to be efficiently skipped add // !codeanalysis e.g. // AUTOGENERATED FILE // +build !codeanalysis package foo