others-how to solve 'declared but not used' when running golang program ?

Problem

When we run a golang progam , sometimes , we get this error:

➜  hello1 go run main.go
# command-line-arguments
./main.go:32:6: idx declared but not used

Why do this error happen? The program is correct, I promise!!!

Environment

  • go version go1.14 darwin/amd64

The code

	for idx,book:=range Books {
		fmt.Printf("%v\n",book)
	}

I am iterating a slice, and trying to print all the books. But I got this:

./main.go:32:6: idx declared but not used

Why?

Reason

Golang is different from othere languages, you should use a variable if you declare it, otherwise, the go runtime would complain and print error ‘xxx declared but not used’.

Solution

We can use blank identifier (_) to replace the variable that we don’t want to use:

	for _,book:=range Books {
		fmt.Printf("%v\n",book)
	}

The key point is :

for _,book:=range Books {

What is blank identifier?

The blank identifier can be assigned or declared with any value of any type, with the value discarded harmlessly. It’s a bit like writing to the Unix /dev/null file: it represents a write-only value to be used as a place-holder where a variable is needed but the actual value is irrelevant. It has uses beyond those we’ve seen already.

Aside from being used in assignment, the blank identifier can also be used in imports as follows:

import (
    _ "strconv" // if you don't use this package, it would avoid error
)

Run the app again, No error messages ,It works!

By the way

Accordint to this link,you’d better try to use every variable you defined:

The presence of an unused variable may indicate a bug, while unused imports just slow down compilation. Accumulate enough unused imports in your code tree and things can get very slow. For these reasons, Go allows neither.

 return "home_admin";

Run the app again, No error messages ,It works!