rust-cookbook/README.md

68 lines
1.7 KiB
Markdown
Raw Normal View History

2017-02-21 22:41:35 +00:00
# Cookin' with Rust
A practical guide to the Rust crate ecosystem.
## Recipes
### [Byteorder](pages/byteorder.md) [![byteorder][byteorder-badge]][byteorder]
2017-02-21 22:41:35 +00:00
## A note about error handling
2017-02-21 22:41:35 +00:00
Error handling in Rust is robust when done correctly, but in today's
Rust it requires a fair bit of boilerplate. Because of this one often
sees Rust examples filled with `unwrap` calls instead of proper error
2017-02-21 22:41:35 +00:00
handling.
Since these recipes are intended to be reused as-is and encourage best
practices, they set up error handling correctly, and when necessary to
reduce boilerplate, they use the [error-chain] crate.
The code for this setup generally looks like:
```rust
2017-02-25 05:21:08 +00:00
#[macro_use]
extern crate error_chain;
2017-02-21 22:41:35 +00:00
mod errors {
error_chain! {
foreign_links {
Io(::std::io::Error);
}
}
}
use errors::*;
fn main() { run().unwrap() }
fn run() -> Result<()> {
2017-02-25 05:21:08 +00:00
use std::io::Write;
let ref mut stdout = ::std::io::stdout();
2017-02-21 22:41:35 +00:00
writeln!(stdout, "hello, world")?;
Ok(())
}
```
This is using the `error_chain!` macro to define a custom `Error`
and `Result` type, along with an automatic conversion from
the common `::std::io::Error` type. The automatic conversion
makes the `?` operator work
For more background on error handling in Rust, read [this page of the Rust book][error-docs] and [this blog post][error-blog].
2017-02-21 22:41:35 +00:00
2017-02-25 08:25:51 +00:00
## Contributing
If you'd like to make changes to the project, please see [this guide](CONTRIBUTING.md).
2017-02-21 22:41:35 +00:00
## License
2017-02-21 22:41:35 +00:00
MIT/Apache-2.0
<!-- Links -->
2017-02-25 08:47:26 +00:00
[byteorder-badge]: https://img.shields.io/crates/v/rustc-serialize.svg?label=byteorder
2017-02-21 22:41:35 +00:00
[byteorder]: https://docs.rs/byteorder
[error-docs]: https://doc.rust-lang.org/book/error-handling.html
[error-blog]: https://brson.github.io/2016/11/30/starting-with-error-chain