我試圖弄清楚如何將文件中的特定行解析為 au32
但是method not found in Option<String>
當我嘗試解析Option<String>
.
有沒有辦法解析它,或者我是否在接近這個錯誤?
use std::io::{BufRead, BufReader};
use std::fs::File;
fn main() {
let reader = BufReader::new(File::open("input").expect("Cannot open file"));
let lines = reader.lines();
let number: u32 = lines.nth(5).unwrap().ok().parse::<u32>();
println!("{}", number);
}
您無法從 中解析出一個數字Option<String>
,因為如果是None
,則沒有什麼可解析的。您必須解開第Option
一個(或進行適當的錯誤處理):
use std::io::{BufRead, BufReader};
use std::fs::File;
fn main() {
let reader = BufReader::new(File::open("input").expect("Cannot open file"));
let number: u32 = reader.lines()
.nth(5)
.expect("input is not 5 lines long")
.expect("could not read 5th line")
.parse::<u32>()
.expect("invalid number");
println!("{}", number);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句