空白符的产生可能是因为go不允许变量声明了但不使用。既然不想使用,何必声明变量呢,那就将变量用空白符代替,反正空白符就是用来抛弃的。
1 空白符用来匹配一些不需要的值,然后丢弃掉,下面的 blank_identifier.go 就是很好的例子。
ThreeValues
是拥有三个返回值的不需要任何参数的函数,在下面的例子中,我们将第一个与第三个返回值赋给了 i1
与f1
。第二个返回值赋给了空白符 _
,然后自动丢弃掉。
示例 6.4 blank_identifier.go
package main
import "fmt"
func main() {
var i1 int
var f1 float32
i1, _, f1 = ThreeValues()
fmt.Printf("The int: %d, the float: %f \n", i1, f1)
}
func ThreeValues() (int, int, float32) {
return 5, 6, 7.5
}
输出结果:
The int: 5, the float: 7.500000
2 import时候加空白符
package main
import(
"image"
"image/jpeg" // I wanted to export the images as JPEG
_ "image/png"
_ "image/gif"
)
// ...
表示,只使用被引用包的init函数,只导入png,gif包但不使用,又为避免不使用的错误断定。
3
type T struct{}
var _ I = T{} // Verify that T implements I.
这种情况类似静态断言,断定T{}可以是接口,但又不想再使用结果I.
4
func (env *maasEnviron) Bootstrap(ctx environs.BootstrapContext, args environs.BootstrapParams) (arch, series string, _ environs.BootstrapFinalizer, _ error) {
这种情况?在使用时仍然会正常使用finalizer和err。FIXME
参考
1 资料集合
http://blog.csdn.net/loongshawn/article/details/54112640
2 空白符
https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/06.2.md
3
http://stackoverflow.com/questions/26972615/a-use-case-for-importing-with-blank-identifier-in-golang
To import a package solely for its side-effects (initialization), use the blank identifier as explicit package name.
4
http://stackoverflow.com/questions/24357028/meaning-of-underscore-blank-identifier-in-go
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.
5 go例子
https://gobyexample.com/
PS 使用liteIDE进行编程。liteIDE查找比较方便,关联和其他引用高亮离source insight差很多