golang下划线(underscore) 总结

时间:2023-03-08 22:30:49

一、概述

  "_" 可以简单理解为赋值但以后不再使用,在golang中使用的比较多,使用的场合也很多,稍作总结;

二、场景

  1、import

 import  _ "net/http/pprof"

  引入包,会调用包中的初始化函数,这种使用方式仅让导入的包做初始化,而不适用包中其他功能;

  2、用在返回值

 for _, v := range Slice {}
_, err := func()

  表示忽略某个值。单函数有多个返回值,用来获取某个特定的值

  3、用在变量

 type Interface interface {

 }

 type T struct{

 }

 var _ Interface = &T{}

  上面用来判断 type T是否实现了I,用作类型断言,如果T没有实现借口I,则编译错误.

示例:

 package main

 import "fmt"

 type Interface interface {
Stop()
} type Bmw struct {
Name string
} func (this *Bmw) Stop() {
fmt.Printf("%s bmw stop.\n", this.Name)
} type Car struct {
Interface
} func main() {
c := Car{
&Bmw{
Name: "X5",
},
}
c.Stop()
}