Essential Go Variables  Suggest an edit

Blank identifier

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)           // prints 3
}
3

Using 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

  ↑ ↓ to navigate     ↵ to select     Esc to close