我发现了以下特点:
b := "a"[0]
r := 'a'
fmt.Println(b == r) // Does not compile, cannot compare byte and rune
fmt.Println("a"[0] == 'a') // Compiles and prints "true"
Run Code Online (Sandbox Code Playgroud)
这是如何运作的?
这是无类型常量的示例.来自文档:
无符号布尔值,数字和字符串常量可以用作操作数,分别使用布尔值,数字或字符串类型的操作数是合法的.除了移位操作之外,如果二元操作的操作数是不同类型的无类型常量,则操作和对于非布尔操作,结果使用此列表中稍后出现的类型:整数,符文,浮点数,复数.
由于'a'
是无类型常量,编译器将尝试将其转换为与其他操作数相当的类型.在这种情况下,它会转换为byte
.
当符文常量不适合单个字节时,您可以看到这不起作用:
package main
import (
"fmt"
)
func main() {
const a = '€'
fmt.Println("a"[0] == a) // constant 8364 overflows byte
}
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/lDN-SERUgN
归档时间: |
|
查看次数: |
2577 次 |
最近记录: |