我要从Python进入Rust,并且正在研究Rustlings error exercise #3。
我不确定如何处理Result
函数的total_cost()
返回。我可以在另一个if
语句中包装成本比较if语句,该语句检查cost
变量是什么数据类型?
现在,这就是说我无法在>
数据类型上使用Result<i32, ParseError>
运算符。我是否可以使用assert!(cost: i32)
之类的方法检查数据类型?
这是下面的难题...
use std::num::ParseIntError;
fn main() {
let mut tokens = 100;
let pretend_user_input = "8";
let cost = total_cost(pretend_user_input);
if cost > tokens {
println!("You can't afford that many!");
} else {
tokens -= cost;
println!("You now have {} tokens.", tokens);
}
}
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1;
let cost_per_item = 5;
let qty = item_quantity.parse::<i32>()?;
Ok((qty * cost_per_item) + processing_fee)
}
error[E0369]: binary operation `>` cannot be applied to type `std::result::Result<i32, std::num::ParseIntError>`
--> src/main.rs:10:8
|
10 | if cost > tokens {
| ^^^^^^^^^^^^^
|
= note: an implementation of `std::cmp::PartialOrd` might be missing for `std::result::Result<i32, std::num::ParseIntError>`
error[E0277]: cannot subtract-assign `std::result::Result<i32, std::num::ParseIntError>` from `{integer}`
--> src/main.rs:13:16
|
13 | tokens -= cost;
| ^^ no implementation for `{integer} -= std::result::Result<i32, std::num::ParseIntError>`
|
= help: the trait `std::ops::SubAssign<std::result::Result<i32, std::num::ParseIntError>>` is not implemented for `{integer}`