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

2021年3月16日12:40:46 发表评论 706 次浏览

“_(下划线)”在Golang中称为空白标识符。标识符是用于识别目的的程序组件的用户定义名称。 Golang具有特殊功能, 可使用Blank Identifier定义和使用未使用的变量。未使用的变量是那些

变量

由用户在整个程序中定义, 但他/她从未使用过这些变量。这些变量使程序几乎不可读。如你所知, Golang是一种更加简洁易读的编程语言, 因此如果你这样做, 则它不允许程序员定义未使用的变量, 否则编译器将引发错误。

当函数返回多个值时, 才真正使用Blank Identifier, 但是我们只需要几个值并希望丢弃一些值。基本上, 它告诉编译器不需要此变量, 并且将其忽略而没有任何错误。它隐藏变量的值并使程序可读。因此, 每当你将值分配给Bank Identifier时, 它就变得不可用。

范例1:在下面的程序中, 该功能mul_div返回两个值, 我们将两个值都存储在多和div标识符。但在整个程序中, 我们仅使用一个变量, 即多。所以编译器会抛出错误div已声明且未使用

// 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标识符, 只需使用_(下划线)。它允许编译器忽略声明且未使用该特定变量的错误。

// 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程序可以使用相同的标识符名称(即空白标识符)来包含多个变量。
  • 在很多情况下, 即使知道这些值都不会在程序中的任何地方使用, 也需要分配值来完成语法。就像一个返回多个值的函数。在这种情况下, 通常使用空白标识符。
  • 你可以将任何类型的任何值与空白标识符一起使用。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: