Blank identifier

suggest change

To help avoid mistakes Go compiler doesn’t allow unused variables.

However, there are some situations when you don’t need to use a value stored in a variable.

In those cases, you use a “blank identifier” _ to assign and discard the assigned value.

A blank identifier can be assigned a value of any type, and is most commonly used in functions that return multiple values.

Multiple Return Values

func SumProduct(a, b int) (int, int) {
	return a + b, a * b
}

func main() {
	// only need the sum
	sum, _ := SumProduct(1, 2) // the product gets discarded
	fmt.Println(sum)           // -> 3
}
3

With range

func main() {
	pets := []string{"dog", "cat", "fish"}

	// range returns both the current index and value
	// but sometimes we only need one or the other
	for _, pet := range pets {
		fmt.Println(pet)
	}
}
dog
cat
fish

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents