docs

#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 上編輯此頁 最後更新: