How to Fix declared but not used Error in Golang

The declared but not used error occurs in Golang when you “declare a variable but don’t use it in your code.” It enforces a strict policy to ensure a clean and efficient code.

To fix the declared but not used error in Go, you can use the blank identifier(_)”. The blank identifier(_) temporarily suppresses the error (e.g., during development or debugging, tellings the compiler that you’re intentionally ignoring the variable.

Probability 1: Variable declared and not used anywhere

This is the most straightforward reason for this error. The Go compiler will complain if you declare a variable and don’t use it anywhere in your code. This prevents unused variables from cluttering the code and potentially introducing bugs or confusion later.

Example

package main

import (
  "fmt"
)

func main() {
  kb := 21

  // To fix the error, use the blank identifier
  _ = kb

  fmt.Println("Hello, Gopher!")
}

Output

Hello, Gopher!

Probability 2: Variable declared and used, yet the code crashes

This scenario is a bit more nuanced. If you think you’ve used a variable but still get this error, it’s possible that the code path where the variable is used might not be reachable.

For instance, if the variable usage is inside a conditional block that is never executed or inside a function that is never called, the Go compiler might still consider the variable unused.

Another possibility is when using shadowing. If you declare a variable in an outer scope and then redeclare a variable with the same name in an inner scope, the outer variable might become unused.

Example

package main

import (
  "fmt"
)

func main() {
  var str string

  if false {
    str := "hello"
  } else {
    str := "hello world"
  }

  fmt.Println(str)
}

Output

./service.go:11:3: str declared and not used
./service.go:13:3: str declared and not used

To fix the error and avoid the shadowing, you should “assign to the outer str variable directly, without using the := syntax”.

package main

import (
  "fmt"
)

func main() {

  var str string

  if false {
    str = "hello"
  } else {
    str = "hello world"
  }

  fmt.Println(str)
}

Output

hello world

That’s it.

Leave a Comment