这个问题在这里已有答案:
我想在Rust中将整数转换为字节文字:
for x in 0..10000 {
let key = x.to_???;
other_function(key);
}
无法在文档中找到它。
byte literal
就像b'f'
,写下了字面值。你可能意味着一个byte
,通常是u8
,有时是i8
。你最近可以使用TryFrom
-trait:
use std::convert::TryFrom;
fn main() {
for i in 253..257 {
let u = u8::try_from(i).expect("Not all integers can be represented via u8");
println!("{}", u);
}
}
循环中的u
是一个u8
。代码将打印253,254,255并在迭代时崩溃,其中i
变得大于u8
可以表示的值。