go 下划线用法
忽略返回值
某函数返回三个参数 只需要其中的两个 另外一个参数 忽略
v1, v2, _ := function(...)
用在变量定义接口
用在变量(特别是接口断言) 定义 一个接口(interface):
type Foo interface {
Say()
}
然后定义 一个结构体(struct)
type Dog struct {}
判断Dog 这个struct 是否实现了Foo这个interface
var _ Foo = Dog{}
用作类型断言 如果Dog没有实现Foo 则 报编译错误
初始化包而不使用包其他功能
用在import package 在代码的import中 package引入
import _ "test/foo"
在执行本段代码之前 先调用 test/foo 初始化函数(init) 仅让导入的包 初始化 而不使用包中其他功能
Foo struct 然后 进行初始化
package foo
import "fmt"
type Foo struct {
Id int
Name string
}
func init() {
f := &Foo{Id: 123, Name: "abc"}
fmt.Printf("init foo object: %v\n", f)
}
在main函数里面引入test/foo
package main
import (
"fmt"
_ "test/foo"
)
func main() {
fmt.Printf("hello world\n")
}
运行结果
init foo object: &{123 abc}
hello world
在main函数输出”hello world”之前就 对foo对象进行初始化了
尊贵的董事大人
英文标题不为空时 视为本栏投稿
需要关键字 描述 英文标题