如何正确读取用户输入的字符串('true' 或 'false')作为 bool - true 或 false,然后用它做些什么?没有这种原始方式使用 len()
?
fn main() {
loop {
println!("Input condition - true or false");
let mut condition = String::new();
io::stdin()
.read_line(&mut condition)
.expect("failed to read input.");
let len = calculate_length(&condition);
// println!("The length of '{}' is {}.\n", &condition, &len);
fn calculate_length(condition: &String) -> usize {
condition.len()
}
match len == 5 {
true => {
let number = 100;
println!("The value of number is: {}", &number);
}
_ => {
let number = 7;
println!("The value of number is: {}", &number);
}
};
break;
}
}
最佳答案
你可能想要这样的东西:
let truth_value: bool = match condition {
"true" => true,
"t" => true,
"false" => false,
"f" => false,
... any other cases you want
_ => false // Or whatever appropriate default value or error.
}
那么你的 truth_value
变量将是一个 boolean 值。通常,这种功能嵌入在 FromStr
实现中,但严格来说并非如此。
关于 rust - 真或假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68505340/