Go将字节与符文进行比较的规则是什么? [英] What are Go's rules for comparing bytes with runes?

查看:62
本文介绍了Go将字节与符文进行比较的规则是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了以下特殊之处:

I've discovered the following peculiarity:

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"

这是如何工作的?

推荐答案

这是无类型常量的示例.从文档中:

在合法使用分别为布尔,数字或字符串类型的操作数的任何地方,都可以将未类型化的布尔,数字和字符串常数用作操作数.除移位运算外,如果二进制运算的操作数是不同类型的无类型常量,则该运算以及对于非布尔运算而言,结果将使用此列表稍后显示的类型:整数,符文,浮点数,复数

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 .

Since 'a' is an untyped constant, the compiler will try to convert it to a type comparable with the other operand. In this case, it gets converted to a byte.

当符文常量不适合单个字节时,您会发现此方法不起作用:

You can see this not working when the rune constant does not fit into a single byte:

package main

import (
    "fmt"
)

func main() {
    const a = '€'
    fmt.Println("a"[0] == a) // constant 8364 overflows byte
}

https://play.golang.org/p/lDN-SERUgN

这篇关于Go将字节与符文进行比较的规则是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆