noloopclosure

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2022 License: MIT Imports: 10 Imported by: 3

README

test status

noloopclosure

noloopclosure is a linter that disallow reference capture of loop variable inside of a closure.

This linter can prevent bugs introduced by a very popular gotcha in Go by disallowing implicit reference capture when creating closure inside a loop.

Installation

go install github.com/fatanugraha/noloopclosure/cmd/noloopclosure@latest

Difference with go vet's loopclosure

loopclosure will only complain if the captured loop variable is inside of a function closure that preceded by go and defer keyword and is the last statement in the loop's block (reference).

This linter complain each time it found any captured loop variable inside a function closure. This linter is helpful if you have utilities that abstracts the go behavior, for example:

func main() {
	for i := 0; i < 10; i++ {
		runInGoroutine(func() { fmt.Println(i) })
	}
}

func runInGoroutine(f func()) {
	go f()
}

will pass the go vet's check while fails the noloopclosure check.

It's generally a good idea (unless every bit of performance matters) to extract the function creation part inside your loop so that you don't accidentally capture the reference and cause unwanted bugs. For example, code above can be re-written as:

func main() {
	for i := 0; i < 10; i++ {
		runInGoroutine(newIntPrinter(i))
	}
}

func newIntPrinter(i int) func() {
    func() { fmt.Println(i) }
}

func runInGoroutine(f func()) {
	go f()
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Analyzer = &analysis.Analyzer{
	Name:     "noloopclosure",
	Doc:      "noloopclosure is an analyzer that disallow reference capture of loop variable inside of a closure",
	Run:      run,
	Flags:    flags(),
	Requires: []*analysis.Analyzer{inspect.Analyzer},
}

Functions

This section is empty.

Types

This section is empty.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL