The whitespace identifier is used in Go language to place or ignore variables or values, and the syntax is _. It can be used to discard unnecessary variables, placeholders, and variables with multiple return values from functions. In practice, it can be used to skip unwanted scan results, such as ignoring scanner errors.
Whitespace identifiers are a special type of identifier in Go language symbol, used to place or ignore specific variables or values. Although they may seem inconspicuous, whitespace identifiers can be helpful in certain scenarios.
White space identifiers are represented by the keyword _
. It can only be used as a local variable or function parameter name.
func foo(_ int) {} func main() { var _ = 10 }
When you need to declare a variable, but don't actually use its value, you can use a blank identifier to avoid compilation device warning.
func foo(x int) { if x > 10 { _ = fmt.Println("x is greater than 10") } }
A blank identifier can be used to create a placeholder, indicating that the value will not be used until later.
func foo() (int, int) { // 假设 a 和 b 的值稍后会计算出来 return _, _ }
When the function return value is ignored, a blank identifier can be used as its variable name.
func foo() (int, error) { x, _ := bar() return x, nil // 忽略错误 }
Suppose we have the following code to scan the entered number:
package main import ( "fmt" "strings" ) func main() { scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { line := scanner.Text() if num, err := strconv.Atoi(line); err == nil { fmt.Printf("有效数字:%d\n", num) } } if err := scanner.Err(); err != nil { fmt.Println("读取输入时出错:", err) } }
In this In this example, we only want to print valid numbers without having to deal with scanner errors. We can use a blank identifier to ignore the error:
package main import ( "bufio" "fmt" "os" "strconv" ) func main() { scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { line := scanner.Text() if num, _ := strconv.Atoi(line); err == nil { fmt.Printf("有效数字:%d\n", num) } } _ = scanner.Err() // 忽略扫描器错误 }
The above is the detailed content of Understanding the secrets of whitespace identifiers in Go. For more information, please follow other related articles on the PHP Chinese website!