#E0134: 资源没有关闭
关闭这个值可能失败(它的类型实现了 io::Close),所以不会自动替你关闭:在某条路径上,它在仍然打开时离开了作用域、被替换,或者随着被 try? 丢弃的错误一起被丢弃。在它离开之前加上 try x.close();,用 using x = .. { .. } 绑定它,或者捕获错误并关闭它持有的东西。
nabi
use std::env;
use std::fs::File;
fn main() throws {
let f = try File::create(env::temp_dir() / "notes.txt");
try f.write_all("hi");
}
error[E0134]: `f` holds a `File` that is never closed --> main.nabi:5:17 | 5 | let f = try File::create(env::temp_dir() / "notes.txt"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 6 | try f.write_all("hi"); | ----------------- it is still open when it leaves here | = help: closing a `File` can fail, so it is not closed for you: add `try f.close();` before it leaves its scope, or bind it with `using f = .. { .. }`
在它离开作用域之前关闭它:
nabi
use std::env;
use std::fs::File;
fn main() throws {
let f = try File::create(env::temp_dir() / "notes.txt");
try f.write_all("hi");
try f.close();
println("written");
}
written
调用只是借用的临时值也是如此:在 (try File::open(p)).read_to_str() 或 BufReader::new(try File::open(p)).lines() 中,调用之后没有任何东西拥有这个文件,所以也没有任何东西关闭它。
nabi
use std::fs::File;
use core::io::IoError;
fn whole(path: str) throws (IoError) -> str {
try (try File::open(path)).read_to_str()
}
error[E0134]: the `File` made here is never closed: this call only borrows it --> main.nabi:5:14 | 5 | try (try File::open(path)).read_to_str() | ^^^^^^^^^^^^^^^^ | = help: closing a `File` can fail, so it is not closed for you: bind it with `using` (`using x = .. { .. }`), or bind it and close it (`let x = ..; .. try x.close();`)
用 using 绑定它,它会在块结束时关闭:
nabi
use std::env;
use std::fs;
use std::fs::File;
use std::process;
use core::io::IoError;
fn whole(path: str) throws (IoError) -> str {
using f = try File::open(path) { try f.read_to_str() }
}
fn main() throws (IoError) {
let p = env::temp_dir() / f"nabi_e0134_{process::id()}.txt";
try fs::write(p, "hi");
println(try whole(p.as_str()));
try fs::remove_file(p);
}
hi
相关错误码:E0133 资源在移动或关闭之后又被使用,E0066 对没有 Drop 的值使用 using
发现错误? 在 GitHub 上编辑此页 最后更新: