Read
e Write
Usando Read
e BufRead
, vocĂȘ pode abstrair as fontes de dados do tipo u8
:
use std::io::{BufRead, BufReader, Read, Result}; fn count_lines<R: Read>(reader: R) -> usize { let buf_reader = BufReader::new(reader); buf_reader.lines().count() } fn main() -> Result<()> { let slice: &[u8] = b"foo\nbar\nbaz\n"; println!("linhas na _slice_: {}", count_lines(slice)); let file = std::fs::File::open(std::env::current_exe()?)?; println!("linhas no arquivo: {}", count_lines(file)); Ok(()) }
Da mesma forma, Write
permite abstrair a escrita de dados do tipo u8
:
use std::io::{Result, Write}; fn log<W: Write>(writer: &mut W, msg: &str) -> Result<()> { writer.write_all(msg.as_bytes())?; writer.write_all("\n".as_bytes()) } fn main() -> Result<()> { let mut buffer = Vec::new(); log(&mut buffer, "OlĂĄ")?; log(&mut buffer, "Mundo")?; println!("Registrado: {:?}", buffer); Ok(()) }