目标是制作一个程序,从
56c
或 36f
等输入中,它可以了解我们正在使用的比例,然后进行相应的转换。这是当前的代码:
use std::io;
fn main() {
println!("Please input temp in format 35f/35c: ");
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
let len = input.trim().len();
let unit = &input[len - 1..];
input.truncate(len - 1);
if unit == "f" {
let result = fahrenheit_to_c(input.parse::<i32>().unwrap());
println!("{result}");
} else if unit == "c" {
let result = celsius_to_f(input.parse::<i32>().unwrap());
println!("{result}");
} else {
println!("Please make the correct input!");
}
}
fn fahrenheit_to_c(tempr: i32) -> i32 {
(tempr - 32) * 5 / 9 as i32
}
fn celsius_to_f(tempr: i32) -> i32 {
(tempr * 9 / 5) + 32 as i32
}
当我在没有 Result
语句的情况下测试它时,
if
输出有效,在我添加 if
语句后,我开始得到这个
error[E0502]: cannot borrow `input` as mutable because it is also borrowed as immutable
--> src/main.rs:13:5
|
12 | let unit = &input[len - 1..];
| ----- immutable borrow occurs here
13 | input.truncate(len - 1);
| ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
14 | if unit == "f" {
| ---- immutable borrow later used here
我尝试将比例和温度作为不同的两个不同输入,以使类型转换更简单,但这不是我在这里的目标。
在共享对您仍在使用的
input
的引用后,您将无法对其进行修改。 let unit = &input[len - 1..];
采用对 input
的共享引用。
相反,您可以通过简单的
value
获得两个分开的切片,unit
和 split_at
:
let (value, unit) = input.split_at(len - 1);
现在您可以解析该
value
并使用 unit
来决定如何处理它。