本页尚未翻译,以下为英文原文。
#E0134: resource not closed
Closing this value can fail (its type implements io::Close), so it is not closed for you: on some path it leaves its scope, is replaced, or is dropped with an error that try? discards, while still open. Add try x.close(); before it leaves, bind it with using x = .. { .. }, or catch the error and close what it holds.
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 = .. { .. }`
Close it before it leaves its scope:
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
A temporary that a call only borrows is the same: in (try File::open(p)).read_to_str() or BufReader::new(try File::open(p)).lines(), nothing owns the file after the call, so nothing closes it.
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();`)
Bind it with using, which closes it when the block ends:
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
Related: E0133 resource used after it was moved or closed, E0066 using on a value without Drop
Found a mistake? Edit this page on GitHub. Last updated