So! Rust futures! Easy peasy lemon squeezy. Until it's not. So let's do the easy thing, and then instead of waiting for the hard thing to sneak up on us, we'll go for it intentionally.
Choo choo here comes the easy part 🚂💨
We make a new project:
Shell session$ cargo new waytoodeep
Created binary (application) `waytoodeep` package
We install cargo-edit
in case we don't have it yet, so we can just cargo add
later:
Shell session$ cargo install cargo-edit
Updating crates.io index
Downloaded cargo-edit v0.7.0
Downloaded 1 crate (57.6 KB) in 0.47s
Ignored package `cargo-edit v0.7.0` is already installed, use --force to override
Yeah, because it's really convenient. Readers just get confused because subcommands like cargo new
, cargo build
, cargo test
, cargo run
etc. are built into cargo, but cargo add
isn't.
Then we pick an async runtime, because those futures won't poll themselves... and we'll pick tokio for no reason other than: that's what I've been using a bunch these past few months.
Shell session$ cargo add tokio@1.9.0 --features full
Updating '<https://github.com/rust-lang/crates.io-index>' index
Adding tokio v1.9.0 to dependencies with features: ["full"]
Then we change up our main so it uses a default tokio executor (cargo new
generated one for us, but it's not adequate here):
Rust code// in `src/main.rs`#[tokio::main]
asyncfnmain() {
println!("Hello from a (so far completely unnecessary) async runtime");
}
Shell session$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/waytoodeep`
Hello from a (so far completely unnecessary) async runtime
Cool!
But let's add some other nice things I just like to have in my projects.
First, for error handling - we're writing an app, we're going to get a bunch of different types from different libraries, it'd be neat if we could have one type to unify them all.
eyre gives us that (just like anyhow
)!
And since I like pretty colors I'll use color-eyre
Shell session$ cargo add color-eyre@0.5.11
Updating '<https://github.com/rust-lang/crates.io-index>' index
Adding color-eyre v0.5.11 to dependencies
Now we need to install color-eyre
as the default panic handler, and I snuck in some environment variable modification so we get backtraces by default.