我在打印过程中遇到了这种异常行为:
use std::io;
fn main() {
let mut number = String::new();
io::stdin()
.read_line(&mut number)
.expect("Failed to read line");
let mut number_len = number.len();
number.truncate(number_len - 1); // removing trailing \n
number_len = number.len();
println!("Number entered is {} with length {}", number, number_len);
for i in 0..(number_len - 1) {
println!("Char at {} is {}", i, &number[i..i + 1]);
}
}
输出
4200 <- my input
with length 5 is 4200 <- Oddly printed output
Char at 0 is 4
Char at 1 is 2
Char at 2 is 0
Char at 3 is 0
为什么会这样?
此外,number
的长度是错误的...它应该是4,而即使在截断后它也会打印5。