https://www.snoyman.com/blog/2018/11/rust-crash-course-04-crates-more-iterators

I also blog frequently on the Yesod Web Framework blog, as well as the FP Complete blog.

See a typo? Have a suggestion? Edit this page on Github

I’m getting bored with bouncy, this is our third week talking about this program. It’s time to finish this off! How do we do double buffering? It’s time to learn about external libraries in Rust, or crates.

This post is part of a series based on teaching Rust at FP Complete. If you’re reading this post outside of the blog, you can find links to all posts in the series at the top of the introduction post. You can also subscribe to the RSS feed.

We still haven’t fixed our double buffering problem, let’s finally do that. We’re also going to introduce some more error handling from the standard library. And then we’ll get to play a bit more with iterators as well.

Finding a crate

To do double buffering in the terminal, we’re going to want some kind of a curses library. We’re going to look for a crate on crates.io. On that page, search for “curses”. Looking through the download counts and the descriptions, pancurses looks nice, especially since it supports Unix and Windows. Let’s use it!

Side note If you’re wondering, this is exactly the process I went through when writing up bouncy. I had no prior knowledge to tell me pancurses was going to be the right choice. Also, this program happens to be the first time I’ve ever used a curses library.

Starting a project

We’re going to create a new project for this using cargo new. We’re going to pull in the bouncy code from the end of week 2 (before the introduction of command line parsing), since as we’ll see later, we won’t need that parsing anymore.

$ cargo new bouncy4
$ cd bouncy4
$ curl <https://gist.githubusercontent.com/snoyberg/5307d493750d7b48c1c5281961bc31d0/raw/8f467e87f69a197095bda096cbbb71d8d813b1d7/main.rs> > src/main.rs
$ cargo run

The ball should be bouncing around your terminal, right? Great!

Adding the crate

The configuration for your project lives in the file Cargo.toml, known as the manifest. On my system, it looks like this:

[package]
name = "bouncy4"
version = "0.1.0"
authors = ["Michael Snoyman <michael@snoyman.com>"]

[dependencies]

It will look a bit different on your machine (unless your name is also Michael Snoyman). Notice that [dependencies] section at the end? That’s where we add information on external crates. If you go back to the pancurses page on crates.io, you’ll see:

Cargo.toml  pancurses = "0.16.0"

It may be different when you’re reading this. That’s telling us what we can add to the dependencies section to depend on the library. There are lots of details about how to specify dependencies, which we won’t get into here (and probably never will in the crash course, I’ve spent enough of my life discussing dependency management already :) ). You can read more in the Cargo book reference.