Bik*_*ire 0 type-conversion rust
对于我为锻炼而做的练习(扫雷任务),我需要将 an 转换usize为 achar以便将其插入到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:
Run Code Online (Sandbox Code Playgroud)
我目前这样做的方式是:
mine_count.to_string().chars().nth(0).unwrap(); // For example: '2'
Run Code Online (Sandbox Code Playgroud)
或者在 rust playground 中查看完整示例。不知何故,这并不让我觉得优雅。
我也试过:
mine_count as char; // where mine_count is of type u8
Run Code Online (Sandbox Code Playgroud)
但是,当添加mine_count到 a 时,std::string::String它会变成 - 例如 -\u{2}而不仅仅是'2':
let mine_count: u8 = 8;
s.insert(0, mine_count as char);
println!("{:?}", s);
Run Code Online (Sandbox Code Playgroud)
输出:
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:
Run Code Online (Sandbox Code Playgroud)
转载在这里。
还有其他方法可以实现将 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);
}
Run Code Online (Sandbox Code Playgroud)
However when adding
mine_countto astd::string::Stringit turns up as - for example -\u{2}and not simply'2'.
This is the difference between the char containing the scalar value 2 and a char containing the actual character '2'. The first few UTF-8 values, like in ASCII text encoding, are reserved for control characters, and do not portray something visible. What made it appear as \u{2} in this context is because you printed the string with debug formatting ({:?}). If you try to print the same string with plain formatting:
let mut s = String::from(" ");
let mine_count: u8 = 8;
s.insert(0, mine_count as char);
println!("{}", s);
Run Code Online (Sandbox Code Playgroud)
The output will contain something that wasn't meant to be printed, and so might either show a placeholder character or not appear at all (reproducible here).
为了将一位数表示为相应的字符: (1) 首先mine_count通过可恢复的错误或硬断言确保在预期的限制内。(2) 然后,通过将数字转换为数字数字字符域来转换数字。
assert!(mine_count > 0);
assert!(mine_count < 9);
let mine_char = (mine_count + b'0') as char;
s.insert(0, mine_char);
println!("{}", s);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3067 次 |
| 最近记录: |