golang中的下划线(_)用法


_ 符号虽然看似不起眼,但是会经常出现。所以还是总结下

1.忽略某个返回值
package main

import(
    "fmt" //内置模块

)

// 定义一个返回两个值的函数
func calculate测试返回值忽略(a, b int) (int, string) {
    errorstr:="a,b不能同时为负"
    if a < 0 || b < 0 {
        return 0, errorstr
    }
    return a + b, errorstr
}
/测试不想要第二个
func divide(a, b int) (int, int) {
return a / b, a % b
}

func main(){
result, _ := calculate测试返回值忽略(5, -1)
    fmt.Println("计算结果:", result) // 输出 0,因为输入了负数

//这里忽略第二个返回值
_, remainder := divide(10, 3)
fmt.Println("余数:", remainder) // 输出 1

}

2.测试使用

//https://go101.org/article/operators.html
func 关于下划线(){
    //The ones compile okay.
    _ = 12 + 'A' // two numeric untyped operands
    _ = 12 - a   // one untyped and one typed operand
    _ = a * b    // two typed operands
    _ = c % d
    _, _ = c + int16(e), uint8(c) + e
    _, _, _, _ = a / b, c / d, -100 / -9, 1.23 / 1.2
    _, _, _, _ = c | d, c & d, c ^ d, c &^ d
    _, _, _, _ = d << e, 123 >> e, e >> 3, 0xF << 0
    _, _, _, _ = -b, +c, ^e, ^-1

    // The following ones fail to compile.
    _ = a % b   // error: a and b are not integers
    _ = a | b   // error: a and b are not integers
    _ = c + e   // error: type mismatching
    _ = b >> 5  // error: b is not an integer
    _ = c >> -5 // error: -5 is not representable as uint

    _ = e << uint(c) // compiles ok
    _ = e << c       // only compiles ok since Go 1.13
    _ = e << -c      // only compiles ok since Go 1.13,
    // will cause a panic at run time.
    _ = e << -1      // error: right operand is negative

}

3.屏蔽或丢弃key或索引(这个用法非常常见在go源码中)

    //数组int,只要取得值时,for _ value:=range 数组{}
        numbers := []int{1, 2, 4, 8, 16}
        //仅仅是值被使用; 索引会被忽略 '_'
        for _, value := range numbers {
            fmt.Printf("Value: %d\n", value)
        }

4.移位操作

//移位操作
func bytes使用(b []byte,v uint64){
    //检测包b的输入验证,如果b[3]则抛出异常
    _ = b[2] // early bounds check to guarantee safety of writes below
    b[0] = byte(v)
    b[1] = byte(v >> 8)
    b[2] = byte(v >> 16)
    fmt.Println(b)

}

5.占位(跳过这个值)

/*
跳值占位(结合iota使用)
如果某个值不需要,可以使用占位符 _,它不是空行,会进行计数,起到跳值作用:
iota 是 Go 语言中的一个常量计数器,用于简化常量的定义。它只能在常量的 const 表达式中使用,
并且在 const 关键字出现时会被重置为 0。每新增一行常量声明,iota 的值会自增 1
*/
const (
    c_a = iota // 0
    _  //占位符
    c_b // 2
)

 


 

posted @ 2025-12-12 13:45  jinzi  阅读(3)  评论(0)    收藏  举报