如何在Rust中将整数转换为字节文字? [重复]

问题描述 投票:-4回答:1

这个问题在这里已有答案:

我想在Rust中将整数转换为字节文字:

for x in 0..10000 {
  let key = x.to_???;
  other_function(key);
}

无法在文档中找到它。

rust
1个回答
4
投票

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可以表示的值。

© www.soinside.com 2019 - 2024. All rights reserved.