Rust中如何将字节字面量转为u64字面量并用于match?
Rust字节字面量转u64用于match的问题
问题描述
我原本以为b'2'u64这种写法合法,但编译时出现报错:
error: suffixes on byte literals are invalid
--> src/main.rs:8:5
|
8 | b'1'u64
| ^^^^^^^ invalid suffixu64error: could not compile
testcondue to previous error
尝试用b'1' as u8 as u32转换类型,但这种写法无法在match语句中使用。想知道如何获取与字节字面量关联、且能用于match的u64字面量?
解决方法
1. 定义常量
将字节字面量转换为u64后定义成编译期常量,就能在match中直接引用:
const ONE: u64 = b'1' as u64; fn main() { let target: u64 = 49; match target { ONE => println!("匹配到'1'对应的u64值"), _ => println!("无匹配"), } }
2. 直接使用字节的ASCII数值
字节字面量b'1'对应的ASCII值是49,直接写49u64即可作为match的分支条件:
fn main() { let target: u64 = 49; match target { 49u64 => println!("匹配到'1'对应的u64值"), _ => println!("无匹配"), } }
3. 批量定义常量(Rust 1.75+)
如果需要处理多个字节值,可用const块批量定义,保持代码整洁:
const { const ONE: u64 = b'1' as u64; const TWO: u64 = b'2' as u64; } fn main() { let target: u64 = 50; match target { ONE => println!("匹配到'1'"), TWO => println!("匹配到'2'"), _ => println!("无匹配"), } }
以上方案都能生成编译期常量,满足match分支对常量表达式的要求。
内容的提问来源于stack exchange,提问作者GumGun
相关产品推荐
相关产品推荐

