"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Ignore Unused Variables in Go\'s SQL Exec() Function?

How to Ignore Unused Variables in Go\'s SQL Exec() Function?

Published on 2024-11-26
Browse:413

How to Ignore Unused Variables in Go\'s SQL Exec() Function?

Go: Ignoring Unused Variables in SQL Statements

When executing SQL statements in Go using the "Exec()" function, multiple values are returned, including a Result object that represents the number of affected rows. However, declaring this Result object unnecessarily can result in compilation errors if the variable is unused.

To address this, the blank identifier (_) can be used to ignore the Result object while still allowing the "Exec()" function to execute. The blank identifier serves as a placeholder for unused values in assignments.

For instance, consider the following code:

stmt, err := db.Prepare("INSERT person SET name=?")
sqlRes, err := stmt.Exec(person.Name)

Here, sqlRes is unused, leading to a compilation error. By replacing sqlRes with _, the code will compile successfully:

stmt, err := db.Prepare("INSERT person SET name=?")
_, err = stmt.Exec(person.Name)

Using the blank identifier allows you to ignore the Result object while maintaining the functionality of the "Exec()" function. This technique can be useful in situations where you only need to execute the SQL statement without capturing the affected rows count.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3