实现说明
from_utf8 失败把字节还给你以函数 main为骨架。
match 表达式是穷尽的——编译器强制没有遗漏的分支。
使用要点
- 每一步打印都带着自己的标签:
decoded:、valid up to、invalid byte at。
常见问题
运行「from_utf8 失败把字节还给你」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 decoded:、valid up to、invalid byte at 这类标签。
核心语句
let repaired: Vec<u8> = raw.iter().map(|b| if *b < 0x80 { *b } else { b'?' }).collect();
代码示例
fn main() {
// Build invalid UTF-8: 0xFF is not a legal lead byte for anything
let payload: Vec<u8> = vec![b'o', b'k', 0xFF, b'!'];
match String::from_utf8(payload) {
Ok(text) => println!("decoded: {text}"),
Err(err) => {
// The error carries validation facts: the first valid_up_to bytes are valid UTF-8
println!("valid up to {}", err.utf8_error().valid_up_to());
// into_bytes hands the original Vec<u8> back: ownership returns to the caller
let raw: Vec<u8> = err.into_bytes();
println!("invalid byte at {}", raw.iter().position(|b| !b.is_ascii()).unwrap());
// Fix the bad byte and retry with the same allocation
let repaired: Vec<u8> = raw.iter().map(|b| if *b < 0x80 { *b } else { b'?' }).collect();
let text = String::from_utf8(repaired).expect("all-ascii now");
println!("repaired: {text}");
}
}
}