gpt4 book ai didi

rust - 如何将 usize 转换为单个字符?

转载 作者:行者123 更新时间:2023-11-29 08:22:00 24 4
gpt4 key购买 nike

我为 Exercism 做的练习(minesweeper 任务),我需要将 usize 转换为 char 以便将其插入到 std::string::String.

用最少的代码行描述问题:

let mut s = String::from("   ");
let mine_count: usize = 5; // This is returned from a method and will be a value between 1 and 8.
s.insert(0, _______); // So I get: "5 " at the underscores I do:

我目前这样做的方式是:

 mine_count.to_string().chars().nth(0).unwrap(); // For example: '2'

或查看 full example in the Rust playground .不知何故,这并没有让我觉得优雅。

我也试过:

 mine_count as char; // Where mine_count is of type u8

但是,当将 mine_count 添加到 std::string::String 时,它会变成 - 例如 - \u{2} code> 而不是简单的 '2':

let mine_count: u8 = 8;
s.insert(0, mine_count as char);
println!("{:?}", s);

输出:

"\u{8}   "

转载here .

是否有其他方法可以实现将1..8范围内的整数转换为单个字符(char)的目的?

最佳答案

我建议使用 char::from_digit连同使用它所必需的转换(as u32):

use std::char;

fn main() {
let mut s = String::from(" ");
let mine_count: u8 = 8; // or i8 or usize
s.insert(0, char::from_digit(mine_count as u32, 10).unwrap());

println!("{:?}", s);
}

关于rust - 如何将 usize 转换为单个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49939145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com