[英]Idiomatic way to convert ascii array to string in Rust
From a byte array, I want to convert a slice to a string using the ASCII-encoding.从字节数组中,我想使用 ASCII 编码将切片转换为字符串。 The solution解决方案
fn main() {
let buffer: [u8; 9] = [255, 255, 255, 255, 77, 80, 81, 82, 83];
let s = String::from_iter(buffer[5..9].iter().map(|v| { *v as char }));
println!("{}", s);
assert_eq!("PQRS", s);
}
does not seem to be idiomatic, and has a smell of poor performance.看起来不太地道,而且有一股表现不佳的味道。 Can we do better?我们能做得更好吗? Without external crates?没有外部板条箱?
A Rust string can be directly created from a UTF-8 encoded byte buffer like so:可以从 UTF-8 编码的字节缓冲区直接创建 Rust 字符串,如下所示:
fn main() {
let buffer: [u8; 9] = [255, 255, 255, 255, 77, 80, 81, 82, 83];
let s = std::str::from_utf8(&buffer[5..9]).expect("invalid utf-8 sequence");
println!("{}", s);
assert_eq!("PQRS", s);
}
The operation can fail if the input buffer contains an invalid UTF-8 sequence, however ASCII characters are valid UTF-8 so it works in this case.如果输入缓冲区包含无效的 UTF-8 序列,则操作可能会失败,但是 ASCII 字符是有效的 UTF-8 因此它在这种情况下有效。
Note that here, the type of s
is &str
, meaning that it is a reference to buffer
.请注意,这里s
的类型是&str
,这意味着它是对buffer
的引用。 No allocation takes place here, so the operation is very efficient.这里没有分配,因此操作非常高效。
See it in action: Playground link看看它在行动: 游乐场链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.