Part 1: Making a library (5 points)

In this part, you’re going to create a new project using cargo that will build a library and binaries. A library is just a collection of code that we can use in multiple applications. We’ve seen and used several libraries already, rand, colored, and clap. Now it’s time to make your own!

There are several key differences between a binary and a library project.

  • A library project has a src/lib.rs file and a binary project has a src/main.rs file. (The names are configurable by changing the Cargo.toml file, but let’s stick with the defaults unless we have a reason to change the names.)
  • Libraries do not have a main function. Instead, they expose types, data, and functions that other code can use.

Your task

Clone the assignment repository (which will be empty) on your machine.

From inside the assignment repo, initialize a new library project using cargo.

$ cargo init --lib --name process

Note that we used cargo init rather than cargo new. The difference is that new will create a new directory whereas init will use an existing one (by default, the current directory, .). We’re using init because we’re not going to have multiple projects inside the repository. It’s more normal to just have a single project per get repo.

At this point, we cannot run $ cargo run because there’s no binary (we’re going to change that momentarily). Indeed, if you look at the files created by running cargo init --lib, you’ll see there’s a src/lib.rs but no src/main.rs. The former is used for a library whereas the latter is used for a binary. Read the code that cargo generated in lib.rs.

Let’s add a binary.

Create a new directory named bin inside the src directory. Inside bin, create a file named runnable.rs. By default, cargo will look inside the src/bin directory and create executables, one per file. In this case, we’re creating an executable runnable that you will implement in Part 3.

For now, create a main function that will call the add method that cargo init generated inside the process library’s lib.rs

mod process { pub fn add(left: usize, right: usize) -> usize { left + right } }
fn main() {
    let result = process::add(5, 10);
    println!("5 + 10 = {result}");
}

Running $ cargo run will now run the runnable program and print 5 + 10 = 15.

If we wanted (and we will later), we could create a new file inside src/bin and then we would have multiple binaries that could use the library code. Neat!

Once you can run $ cargo run, it’s time to move on to next part.