GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • About
  • Home
  • Algorithms
  • Go

This view

  • Original page
  • New address

GeezerVison is showing yourbasic.org — Unused local variables

Unused local variables

yourbasic.org/golang

As you may have noticed, programs with unused local variables do not compile.

func main() {
	var n int // "n declared and not used"
	n = 5     // this doesn't help
}
../main.go:2:6: n declared and not used

This is a deliberate feature of the Go language.

The presence of an unused variable may indicate a bug […] Go refuses to compile programs with unused variables or imports, trading short-term convenience for long-term build speed and program clarity. Go FAQ: Can I stop these complaints about my unused variable/import?

Unused global variables and function arguments are however allowed.

Workaround

If you don’t want to remove or comment out the declaration, you can add a dummy assignment.

func main() {
    	var n int
    	n = 5
        _ = n // n is now "used"
}

Further reading

Learn to love your compiler is a list of common Go compiler error messages: what they mean and how to fix the problem.

Related

Blank identifier (underscore)
The blank identifier is an anonymous placeholder. It can be used to ignore values, import only for side effects, or to silence the compiler.
yourbasic.org

Go Highlights

  • Do you make these Go coding mistakes?
  • Why Go? – Key advantages you may have overlooked
  • Go string handling overview [cheat sheet]
  • Type, value and equality of interfaces
  • Concurrent programming

See all 178 Go articles

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.