use std::fs::File;
fn main() {
let tmp = "tmp.zip";
let save_to_tmp_file = || {
let mut tmp_zip = File::create(tmp)?;
Ok(())
};
save_to_tmp_file();
}
( playground )
构建错误:
error[E0282]: type annotations needed
--> src/main.rs:7:27
|
6 | let save_to_tmp_file = || {
| ---------------- consider giving `save_to_tmp_file` a type
7 | let mut tmp_zip = File::create(tmp)?;
| ^^^^^^^^^^^^^^^^^^ cannot infer type for `_`
最佳答案
你必须指定返回类型:
use std::fs::File;
use std::io;
fn main() {
let tmp = "tmp.zip";
let save_to_tmp_file = || -> Result<(), io::Error> {
let mut tmp_zip = File::create(tmp)?;
Ok(())
};
save_to_tmp_file();
}
关闭有问题。您不能命名闭包的类型;您可以尝试将其缩减为 FnOnce
/FnMut
,但您仍然必须为其提供返回类型。
为了克服您的情况,您可以将 Result
指定为 return type for your main function .
use std::io;
use std::fs::File;
fn main() -> Result<(), io::Error> {
let tmp = "tmp.zip";
let mut tmp_zip = File::create(tmp)?;
Ok(())
}
关于error-handling - 创建使用 try 运算符的闭包时如何修复错误 "type annotations needed"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51476828/