當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Rust WriterPanicked用法及代碼示例


本文簡要介紹rust語言中 Struct std::io::WriterPanicked 的用法。

用法

pub struct WriterPanicked { /* fields omitted */ }

BufWriter::into_parts 中的緩衝數據返回錯誤,當底層編寫器先前發生Panics時。包含(可能部分寫入的)緩衝數據。

示例

use std::io::{self, BufWriter, Write};
use std::panic::{catch_unwind, AssertUnwindSafe};

struct PanickingWriter;
impl Write for PanickingWriter {
  fn write(&mut self, buf: &[u8]) -> io::Result<usize> { panic!() }
  fn flush(&mut self) -> io::Result<()> { panic!() }
}

let mut stream = BufWriter::new(PanickingWriter);
write!(stream, "some data").unwrap();
let result = catch_unwind(AssertUnwindSafe(|| {
    stream.flush().unwrap()
}));
assert!(result.is_err());
let (recovered_writer, buffered_data) = stream.into_parts();
assert!(matches!(recovered_writer, PanickingWriter));
assert_eq!(buffered_data.unwrap_err().into_inner(), b"some data");

相關用法


注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 Struct std::io::WriterPanicked。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。