在读取文件时检测EndOfFile IoResult

tol*_*gap 0 io rust

我正在尝试读取Rust中的文件.我不明白的是:当BufferedReader它在EOF时,它实际上给了一个Err(IoError {kind: EndOfFile}),我不知道如何匹配它.

loop {
  match file.read_line() {
    Ok(line) => {
      // Do stuff
    },
    // Err(EndOfFile) => is want I want here so I can call "break"
    Err(_) => {
      panic!("Unexpected error reading file.");
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如何明确匹配EndOfFile枚举变体?

swi*_*ard 7

如何明确匹配EndOfFile枚举变体?

您可以使用以下模式匹配它而无需额外的嵌套匹配:

loop {
  match file.read_line() {
    Ok(line) => {
      // Do stuff
    },
    Err(IoError { kind: EndOfFile, .. }) =>
      break,
    Err(_) => {
      panic!("Unexpected error reading file.");
    }
  }
}
Run Code Online (Sandbox Code Playgroud)