如何在 Rust 中将字符串(String 或 &str)转换为整数(int)?
大家好!我刚开始学习 Rust,从 Python 转过来,遇到了一个让我困惑的问题。我需要从标准输入或文本文件中读取一个数字,并对其进行算术运算。
在 Python 中,这只需一行代码:`number = int(input())`。但在 Rust 中,我遇到了编译错误。
以下是我的代码,它无法工作:
```rust
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input)
.expect("无法读取字符串");
let number: i32 = input; // 错误!类型不匹配
println!("输入的数字:{}", number + 10);
}
```
编译器报错:`expected i32, found struct String`。我知道 `read_line` 返回的是字符串,而不是数字。但我该如何转换它?
我尝试使用 `parse()`,但遇到了另一个错误:`error[E0282]: type annotations needed`。有人能解释一下将字符串转换为整数的正确方法吗?