Golang 中下划线的作用

golang中的下划线有3种用法。

  1. 忽略返回值
    比如某个函数返回三个参数,但是只需要其中的俩个,另外一个参数可以忽略:

    v1,v2,_ := function(...)
  2. 用在变量(特别是接口断言)
    如果定义了一个接口(interface):

    type Foo interface{
     Say()
    }

    然后定义了一个结构体(struct)

    type Dog struct {
    }

    然后希望在代码中判断Dog 这个struct 是否实现了Foo 这个interface

    var _Foo = Dog{}

    上面用来判断Dog 是否实现了Foo,用作类型断言,如果Dog没有实现Foo,则会报编译错误

  3. 用来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对象进行初始化了!

版权声明:本文为CSDN博主「y果子」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:blog.csdn.net/ayqy42602/article/de...

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 4
  1. go1.13 之后 _ 用在数字之间做为分隔符, 提高可读性
     num := 100_000_000
     fmt.Println(num) // 100000000

    go1.13 Release Note Digit separators: The digits of any number literal may now be separated (grouped) using underscores, such as in 1_000_000, 0b_1010_0110, or 3.1415_9265. An underscore may appear between any two digits or the literal prefix and the first digit.

1年前 评论

那这个下划线呢

file

1年前 评论
my38778570 (楼主) 1年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!