Go 比较字节和符文的规则是什么?
What are Go's rules for comparing bytes with runes?
我发现了以下特点:
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"
这是如何工作的?
符文文字 'a' 表示一个符文常量。常量可以是无类型的。简而言之,声明形式 r := 'a'
rune 常量 'a'
被隐式转换为其默认类型 rune
。但是您可以通过分配给类型化变量来显式转换它。
var r byte = 'a'
这是untyped constants的一个例子。来自文档:
Untyped boolean, numeric, and string constants may be used as operands wherever it is legal to use an operand of boolean, numeric, or string type, respectively. Except for shift operations, if the operands of a binary operation are different kinds of untyped constants, the operation and, for non-boolean operations, the result use the kind that appears later in this list: integer, rune, floating-point, complex.
由于'a'
是一个无类型常量,编译器会尝试将其转换为可与其他操作数进行比较的类型。在这种情况下,它被转换为 byte
.
当符文常量不适合单个字节时,您可以看到这不起作用:
package main
import (
"fmt"
)
func main() {
const a = '€'
fmt.Println("a"[0] == a) // constant 8364 overflows byte
}
我发现了以下特点:
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"
这是如何工作的?
符文文字 'a' 表示一个符文常量。常量可以是无类型的。简而言之,声明形式 r := 'a'
rune 常量 'a'
被隐式转换为其默认类型 rune
。但是您可以通过分配给类型化变量来显式转换它。
var r byte = 'a'
这是untyped constants的一个例子。来自文档:
Untyped boolean, numeric, and string constants may be used as operands wherever it is legal to use an operand of boolean, numeric, or string type, respectively. Except for shift operations, if the operands of a binary operation are different kinds of untyped constants, the operation and, for non-boolean operations, the result use the kind that appears later in this list: integer, rune, floating-point, complex.
由于'a'
是一个无类型常量,编译器会尝试将其转换为可与其他操作数进行比较的类型。在这种情况下,它被转换为 byte
.
当符文常量不适合单个字节时,您可以看到这不起作用:
package main
import (
"fmt"
)
func main() {
const a = '€'
fmt.Println("a"[0] == a) // constant 8364 overflows byte
}