Unused variables

August 15, 2023

Variable declarations

Implementation restriction: A compiler may make it illegal to declare a variable inside a function body if the variable is never used.

One short sentence. And people either love it, or hate it.

I’m in the “love it” camp, but some people like the option to create unused variables, for later use, or during debugging.

func foo() error {
  var i int
  // Some commented out code that probably used i
  // ...
  return nil
}

Fails to compile, complaining “i declared and not used”.

How can you get around this restriction?

Enter the blank identifier. We’ve talked about this guy before.

If you really want to keep around an unused variable, you need to fool the compiler into seeing it as used:

func foo() error {
  var i int
  _ = i
  // Some commented out code that probably used i
  // ...
  return nil
}

Quotes from The Go Programming Language Specification Version of August 2, 2023


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


Assignment statements

Assignment statements An assignment replaces the current value stored in a variable with a new value specified by an expression. Assignments should be familiar to you. They’re pretty fundamental to almost all programming languages. But there are a few aspects to Go’s assignments that are worth calling out. … An assignment statement may assign a single value to a single variable, or multiple values to a matching number of variables.


No short declarations at package level

A couple last points about short variable declarations before we move on… Short variable declarations … Short variable declarations may appear only inside functions. In some contexts such as the initializers for “if”, “for”, or “switch” statements, they can be used to declare local temporary variables. So first: package foo id := 1 // Invalid. Short declarations only possible within fucntions var id = 1 // But this is valid. Don’t ask me why this rule exists.


Short variable declarations, cont'd

Today we’ll look at one of the most interesting, and I would say, confusing, aspects of short variable declarations. Short variable declarations … Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration.

Get daily content like this in your inbox!

Subscribe