将字节字面值转换为u64字面值

huangapple go评论55阅读模式
英文:

getting a byte literal to a u64 literal

问题

I understand that you want a translation of the code-related text. Here is the translated text:

根据此链接,我理解应该允许使用 b'2'u64,但我收到了一个错误

error: 字节字面值上的后缀无效
 --> src/main.rs:8:5
  |
8 |     b'1'u64
  |     ^^^^^^^ 无效的后缀 `u64`

error: 由于先前的错误,无法编译 `testcon`

我发现可以使用 b'1' as u8 as u32,但不能在 match 中使用它。有没有办法获得与字节字面值相关联且可以在 match 中使用的字面值呢?

英文:

I understand based on this link that b'2'u64 should be allowed but I'm getting a error

error: suffixes on byte literals are invalid
 --> src/main.rs:8:5
  |
8 |     b'1'u64
  |     ^^^^^^^ invalid suffix `u64`

error: could not compile `testcon` due to previous error

I found i could use b'1' as u8 as u32 but that is not allowed to use it in a match.
is there any way to get a literal that is linked to a byte literal and can be used for match

答案1

得分: 3

在同一参考页面上,有一个关于后缀的部分。以下是相关段落(重点是我的):

任何带有后缀的文字(字符串、整数等)都有效作为标记

但是,对于被解释为文字表达式或模式的文字标记,后缀受到限制。非数值文字标记上会拒绝任何后缀,只有数值文字标记才能接受下面列表中的后缀。

所以 b'1'u64 在词法上是有效的,甚至可以被宏解析和使用。然而,它在语义上是无效的。在链接的参考中,字节文字创建的只是一个 u8


对于在 match 模式中使用的内容,你可以创建一个常量:

const ONE: u64 = b'1' as u64;

match x {
    ONE => ...,
    ...
}
英文:

Separately on the same reference page is a section on suffixes. Here's the relevant paragraphs (emphasis mine):

> Any kind of literal (string, integer, etc) with any suffix is valid as a token.
>
> However, suffixes on literal tokens which are interpreted as literal expressions or patterns are restricted. Any suffixes are rejected on non-numeric literal tokens, and numeric literal tokens are accepted only with suffixes from the list below.

So b'1'u64 is lexically valid, and can even be parsed and used by macros. However, it is not semantically valid. And in the linked reference, a byte literal creates just that: a single u8.


For something you can use in a match pattern, you could create a constant:

const ONE: u64 = b'1' as u64;

match x {
    ONE => ...,
    ...
}

huangapple
  • 本文由 发表于 2023年5月22日 01:16:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76301068.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定