Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Unused variable

Tags:

go

I am trying to execute a SQL statement in the code below. However, sqlRes is unused and therefore cannot be compiled. I do not need the variable, but I need to declare it because Exec() returns multiple values.

How do I approach this?

stmt, err := db.Prepare("INSERT person SET name=?")
sqlRes, err := stmt.Exec(person.Name)
like image 806
Patrick Reck Avatar asked Nov 19 '15 11:11

Patrick Reck


People also ask

What is an unused variable?

Unused variable %r. Description: Used when a variable is defined but not used.

How do you avoid declared but not used?

To avoid this error – Use a blank identifier (_) before the package name os. In the above code, two variables name and age are declared but age was not used, Thus, the following error will return. To avoid this error – Assign the variable to a blank identifier (_).

What does unused variable mean in C?

No nothing is wrong the compiler just warns you that you declared a variable and you are not using it. It is just a warning not an error. While nothing is wrong, You must avoid declaring variables that you do not need because they just occupy memory and add to the overhead when they are not needed in the first place.

Is declared but not used Golang?

It means that you have declared a variable in the code but did not used it anywhere. This makes the code crash because go wants you to write clean code which is easy to understand and use every variable you declare.


1 Answers

Replace sqlRes with the blank identifier (_). From the spec:

The blank identifier provides a way to ignore right-hand side values in an assignment:

_ = x       // evaluate x but ignore it
x, _ = f()  // evaluate f() but ignore second result value

Example:

stmt, err := db.Prepare("INSERT person SET name=?")
_, err = stmt.Exec(person.Name)
like image 121
Tim Cooper Avatar answered Sep 28 '22 03:09

Tim Cooper