You've already forked comprehensive-rust
mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-07-05 06:00:30 +02:00
I've taken some work by @fw-immunant and others on the new organization of the course and condensed it into a form amenable to a text editor and some computational analysis. You can see the inputs in `course.py` but the interesting bits are the output: `outline.md` and `slides.md`. The idea is to break the course into more, smaller segments with exercises at the ends and breaks in between. So `outline.md` lists the segments, their duration, and sums those durations up per-day. It shows we're about an hour too long right now! There are more details of the segments in `slides.md`, or you can see mostly the same stuff in `course.py`. This now contains all of the content from the v1 course, ensuring both that we've covered everything and that we'll have somewhere to redirect every page. Fixes #1082. Fixes #1465. --------- Co-authored-by: Nicole LeGare <dlegare.1001@gmail.com> Co-authored-by: Martin Geisler <mgeisler@google.com>
49 lines
1.1 KiB
Markdown
49 lines
1.1 KiB
Markdown
---
|
|
minutes: 10
|
|
---
|
|
|
|
# `Read` and `Write`
|
|
|
|
Using [`Read`][1] and [`BufRead`][2], you can abstract over `u8` sources:
|
|
|
|
```rust,editable
|
|
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!("lines in slice: {}", count_lines(slice));
|
|
|
|
let file = std::fs::File::open(std::env::current_exe()?)?;
|
|
println!("lines in file: {}", count_lines(file));
|
|
Ok(())
|
|
}
|
|
```
|
|
|
|
Similarly, [`Write`][3] lets you abstract over `u8` sinks:
|
|
|
|
```rust,editable
|
|
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, "Hello")?;
|
|
log(&mut buffer, "World")?;
|
|
println!("Logged: {:?}", buffer);
|
|
Ok(())
|
|
}
|
|
```
|
|
|
|
[1]: https://doc.rust-lang.org/std/io/trait.Read.html
|
|
[2]: https://doc.rust-lang.org/std/io/trait.BufRead.html
|
|
[3]: https://doc.rust-lang.org/std/io/trait.Write.html
|