golang下划线(underscore) 总结

一、概述

  "_" 可以简单理解为赋值但以后不再使用,在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.
", 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 }
原文地址:https://www.cnblogs.com/chris-cp/p/7158638.html