📜  Golang 中的空白标识符(下划线)是什么?

📅  最后修改于: 2021-10-25 02:12:03             🧑  作者: Mango

_ (下划线)在 Golang 中被称为空白标识符。标识符是用于识别目的的程序组件的用户定义名称。 Golang 有一个特殊功能,可以使用空白标识符来定义和使用未使用的变量。未使用的变量是那些由用户在整个程序中定义但他/她从不使用这些变量的变量。这些变量使程序几乎不可读。如您所知,Golang 是更简洁易读的编程语言,因此它不允许程序员定义未使用的变量,如果这样做,编译器将抛出错误。
当一个函数返回多个值,但我们只需要几个值并且想要丢弃一些值时,Blank Identifier 的真正用途就出现了。基本上,它告诉编译器不需要这个变量并忽略它而没有任何错误。它隐藏变量的值并使程序可读。因此,每当您将值分配给 Bank Identifier 时,它就会变得不可用。

示例 1:在下面的程序中,函数mul_div返回两个值,我们将这两个值存储在muldiv标识符中。但是在整个程序中,我们只使用了一个变量,即mul 。所以编译器会抛出一个错误div declared and not used

// Golang program to show the compiler
// throws an error if a variable is
// declared but not used
  
package main
  
import "fmt"
  
// Main function
func main() {
  
    // calling the function
    // function returns two values which are
    // assigned to mul and div identifier
    mul, div := mul_div(105, 7)
  
    // only using the mul variable
    // compiler will give an error
    fmt.Println("105 x 7 = ", mul)
}
  
// function returning two 
// values of integer type
func mul_div(n1 int, n2 int) (int, int) {
  
    // returning the values
    return n1 * n2, n1 / n2
}

输出:

./prog.go:15:7: div declared and not used

示例 2:让我们使用空白标识符来更正上述程序。代替 div 标识符只需使用 _(下划线)。它允许编译器忽略该特定变量的declared and not used错误。

// Golang program to the use of Blank identifier
  
package main
  
import "fmt"
  
// Main function
func main() {
  
    // calling the function
    // function returns two values which are
    // assigned to mul and blank identifier
    mul, _ := mul_div(105, 7)
  
    // only using the mul variable
    fmt.Println("105 x 7 = ", mul)
}
  
// function returning two 
// values of integer type
func mul_div(n1 int, n2 int) (int, int) {
  
    // returning the values
    return n1 * n2, n1 / n2
}

输出:

105 x 7 =  735

要点:

  • 您可以在同一个程序中使用多个空白标识符。所以你可以说一个 Golang 程序可以有多个变量使用相同的标识符名称,即空白标识符。
  • 在许多情况下,即使知道这些值不会在程序中的任何地方使用,也会出现赋值要求只是为了完成语法。就像一个返回多个值的函数。在这种情况下主要使用空白标识符。
  • 您可以将任何类型的任何值与空白标识符一起使用。