Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of underscore (blank identifier) in Go [duplicate]

Tags:

As I was reading the Go docs I found this:

You can ask the compiler to check that the type T implements the interface I by attempting an assignment:

type T struct{} var _ I = T{} // Verify that T implements I. 

I don't understand what the _ is used for and I've seen it in other assignments but cannot understand what it means. Digging deeper I found that it's called "blank identifier" but I don't understand the use case they put:

_ = x // evaluate x but ignore it 

Go idioms still feel a little alien to me so I'm trying to understand why I would want to do something like this.

like image 226
Julian Avatar asked Jun 23 '14 00:06

Julian


People also ask

What does underscore mean in go?

_(underscore) in Golang is known as the Blank Identifier. Identifiers are the user-defined name of the program components used for the identification purpose. Golang has a special feature to define and use the unused variable using Blank Identifier.

What is a blank identifier?

The blank identifier _ is an anonymous placeholder. It may be used like any other identifier in a declaration, but it does not introduce a binding.

What is blank import in Golang?

About blank identifier go doesn't allow any unused variable. Any unused variable can be replaced by a blank identifier ('_') . So now a blank import of a package is used when. Imported package is not being used in the current program.


1 Answers

_ is a special identifier you can assign anything to but never read from. In the first example you gave:

var _ I = T{} 

There is no way to access this variable so it will be optimised out of the resulting program. However, it could cause a compile error if the type T is not assignable to the interface I. So in this case it is being used as a static assertion about a type.

The second case is more common. While it might seem strange to throw away the result of a function call, it can make more sense in functions with multiple returns. Consider a function foo that returns two values but you're only interested in the first? You can use _ to ignore the second:

a, _ = foo() 

You could get the same effect by creating another variable to hold the unwanted return value, but this feature means you don't need to worry about picking a unique name for it.

like image 108
James Henstridge Avatar answered Sep 30 '22 06:09

James Henstridge