Read 和 Write

您可以使用 ReadBufReadu8 来源进行抽象化处理:

  1. use std::io::{BufRead, BufReader, Read, Result};
  2. fn count_lines<R: Read>(reader: R) -> usize {
  3. let buf_reader = BufReader::new(reader);
  4. buf_reader.lines().count()
  5. }
  6. fn main() -> Result<()> {
  7. let slice: &[u8] = b"foo\nbar\nbaz\n";
  8. println!("lines in slice: {}", count_lines(slice));
  9. let file = std::fs::File::open(std::env::current_exe()?)?;
  10. println!("lines in file: {}", count_lines(file));
  11. Ok(())
  12. }

您同样可使用 Writeu8 接收器进行抽象化处理:

  1. use std::io::{Result, Write};
  2. fn log<W: Write>(writer: &mut W, msg: &str) -> Result<()> {
  3. writer.write_all(msg.as_bytes())?;
  4. writer.write_all("\n".as_bytes())
  5. }
  6. fn main() -> Result<()> {
  7. let mut buffer = Vec::new();
  8. log(&mut buffer, "Hello")?;
  9. log(&mut buffer, "World")?;
  10. println!("Logged: {:?}", buffer);
  11. Ok(())
  12. }