The _ (underscore) is known as the blank identifier in Go. We can use the blank identifier to declare and use the unused variables. The unused variables are the variables that are only defined once in the program and not used. These variables affect the readability of the program and make it unreadable. The unique feature of Go is that it is a readable and concise language. It never allows a variable to be defined and never used; when the variable is defined and not used in a program, it throws an error.
It can ignore values returned by a function
if the value is not needed to make the program readable. We can use it many times in a single program.
It can ignore the effects of unused imports and compiler errors.
package mainimport "fmt"func dummy() (int,int) {val1 := 10val2 := 12return val1,val2}func main(){rVal, _ := dummy()fmt.Println(rVal)}
main
.fmt
for print statements.dummy()
returns two values.rVal
receives the first value returned by the function dummy()
, and _
tells the program to ignore the second value.package mainimport _"fmt"func main(){operand1 := 1operand2 := 2_ = operand1 + operand2}
Line 3: The _
bypasses the error caused by not using the imported library.
Line 8: The _
here tells the compiler to ignore the error for now, and we can add the variable later.
Free Resources