CXJ*_*CXJ 0 error-handling move rust rust-result
以下不编译。使这项工作的规范方法是什么?
let file = File::open(&args.path)?;
let reader = BufReader::new(file);
for line in reader.lines() {
if line?.contains(&args.pattern) {
println!("{}", line?);
}
}
Run Code Online (Sandbox Code Playgroud)
为了完整起见,这是错误消息:
let file = File::open(&args.path)?;
let reader = BufReader::new(file);
for line in reader.lines() {
if line?.contains(&args.pattern) {
println!("{}", line?);
}
}
Run Code Online (Sandbox Code Playgroud)
在您的示例中line是 a Result,它在您使用时被移动?(但我们真的需要Result在您解开其内容之后吗???)。为了缓解您的问题,让我们在同名的局部变量中隐藏的值Result。
for line in reader.lines() {
let line = line?;
if line.contains(&args.pattern) {
println!("{}", line);
}
}
Run Code Online (Sandbox Code Playgroud)