分享
golang下划线(underscore) 总结
chris-cp · · 3707 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
一、概述
"_" 可以简单理解为赋值但以后不再使用,在golang中使用的比较多,使用的场合也很多,稍作总结;
二、场景
1、import
1 import _ "net/http/pprof"
引入包,会调用包中的初始化函数,这种使用方式仅让导入的包做初始化,而不适用包中其他功能;
2、用在返回值
1 for _, v := range Slice {} 2 _, err := func()
表示忽略某个值。单函数有多个返回值,用来获取某个特定的值
3、用在变量
1 type Interface interface { 2 3 } 4 5 type T struct{ 6 7 } 8 9 var _ Interface = &T{}
上面用来判断 type T是否实现了I,用作类型断言,如果T没有实现借口I,则编译错误.
示例:
1 package main 2 3 import "fmt" 4 5 type Interface interface { 6 Stop() 7 } 8 9 type Bmw struct { 10 Name string 11 } 12 13 func (this *Bmw) Stop() { 14 fmt.Printf("%s bmw stop.\n", this.Name) 15 } 16 17 type Car struct { 18 Interface 19 } 20 21 func main() { 22 c := Car{ 23 &Bmw{ 24 Name: "X5", 25 }, 26 } 27 c.Stop() 28 }
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信3707 次点击 ∙ 1 赞
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
一、概述
"_" 可以简单理解为赋值但以后不再使用,在golang中使用的比较多,使用的场合也很多,稍作总结;
二、场景
1、import
1 import _ "net/http/pprof"
引入包,会调用包中的初始化函数,这种使用方式仅让导入的包做初始化,而不适用包中其他功能;
2、用在返回值
1 for _, v := range Slice {} 2 _, err := func()
表示忽略某个值。单函数有多个返回值,用来获取某个特定的值
3、用在变量
1 type Interface interface { 2 3 } 4 5 type T struct{ 6 7 } 8 9 var _ Interface = &T{}
上面用来判断 type T是否实现了I,用作类型断言,如果T没有实现借口I,则编译错误.
示例:
1 package main 2 3 import "fmt" 4 5 type Interface interface { 6 Stop() 7 } 8 9 type Bmw struct { 10 Name string 11 } 12 13 func (this *Bmw) Stop() { 14 fmt.Printf("%s bmw stop.\n", this.Name) 15 } 16 17 type Car struct { 18 Interface 19 } 20 21 func main() { 22 c := Car{ 23 &Bmw{ 24 Name: "X5", 25 }, 26 } 27 c.Stop() 28 }