如何在 Rust 中将 u8 转换为 char?

问题描述 投票:0回答:1

我有一个函数可以根据数组中的 u8 值构建字符串。如果 u8 是 0 或 10,则我压入特定字符。否则,我想推动这个数字本身。我的问题是,当我打印这个函数的结果时,我得到了转义的数字。这是代码:

fn convert_result_to_string(guess_result: &[u8; SEQ_LEN]) -> String {
    let mut output = String::new();

    for (i, num) in guess_result.iter().enumerate() {

        if *num == 0 {
            output.push_str("*");
        }
        else if *num == 10 {
            output.push_str("$");
        }
        else {
            output.push(*num as char);
        }
        if i < SEQ_LEN-1 {
            output.push(' ');
        }
    }

    output
}

然后当我打电话给

let test = [0, 5, 6, 10, 7];
let o = convert_result_to_string(&test);
println!("o: {:?}", o);

我得到以下输出:

o: "* \u{5} \u{6} $ \u{7}"

为什么 5、6、7 会逃脱?

rust encoding utf-8
1个回答
0
投票

您不能只是将

u8
转换为
char
并期望结果显示数字。数字 0-9 由 ASCII(和 Unicode)代码点 48-57 表示。

您可能正在寻找

char::from_digit()

output.push(char::from_digit((*num).into(), 10).expect("digit must be in the range 0-9"));

(游乐场)

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