August Feng

Implementing the Write trait

Well, I did the Read trait so I gotta do the Write trait right?

  use std::io::Write;

  struct Foobar {
      data: String,
  }

  impl std::io::Write for Foobar {
      fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
          let s = std::str::from_utf8(buf).expect("whops");
          self.data.push_str(s);
          Ok(s.len())
      }

      fn flush(&mut self) -> std::io::Result<()> {
          todo!()
      }
  }

  fn main() {
      let mut foobar = Foobar {
          data: String::from("helloworld"),
      };

      let _ = foobar.write(".".as_bytes());
      println!("{}", foobar.data)
  }