Patrick Reck
Patrick Reck

Reputation: 339

Go: Unused variable

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)

Upvotes: 5

Views: 1799

Answers (2)

Zombo
Zombo

Reputation: 1

Another way to avoid the no new variables error is to wrap the check in an if block:

if _, err := stmt.Exec(person.Name); err != nil {
   panic(err)
}

https://golang.org/ref/spec#If_statements

Upvotes: 0

user142162
user142162

Reputation:

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)

Upvotes: 11

Related Questions