go / beginner
Snippet
The Blank Identifier
The blank identifier _ is used when you need to discard a value. It allows you to ignore return values, skip loop indices, or import packages only for initialization side effects. It's like a sink that swallows any value assigned to it.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package mainimport "fmt"func getCoordinates() (x int, y int) {return 10, 20}func main() {x, _ := getCoordinates()fmt.Printf("X: %d\n", x)// Ignore index in rangevalues := []int{1, 2, 3, 4, 5}sum := 0for _, v := range values {sum += v}fmt.Printf("Sum: %d\n", sum)// Import package only for side effect// _ = "fmt"}
Breakdown
1
x, _ := getCoordinates()
Ignores the second return value (y) using the blank identifier
2
for _, v := range values
Blank identifier discards the index, keeping only the value
3
_ = "fmt"
Used to import packages only for side effects (like init() calls)