Fork me on GitHub

Project Notes

Using Cargo

Using Cargo to create and manage a rust project.

Notes

Cargo is the Rust package manager:

  • generates project skeletons
  • downloads package dependencies
  • compiles your packages
  • makes distributable packages
  • uploads distributions to crates.io, the Rust community’s package registry

i.e. similar to bundler and rubygems in the Ruby world.

Making a Project with Cargo

$ cargo new helloc
     Created binary (application) `helloc` package
$ cd helloc/

Generated files:

  • helloc/Cargo.toml - package manifest
  • helloc/src/main.rs - main source file (hello world placeholder)

Building and Run:

$ cargo build
   Compiling helloc v0.1.0 (.../project_with_cargo/helloc)
    Finished dev [unoptimized + debuginfo] target(s) in 1.61s
$ target/debug/helloc
Hello, world!

Alternatively, use cargo run to update compilation and run (like using a makefile)

$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.08s
     Running `target/debug/helloc`
Hello, world!

Build for release

$ cargo build --release
   Compiling helloc v0.1.0 (.../project_with_cargo/helloc)
    Finished release [optimized] target(s) in 1.48s

Adding Dependencies

I’ve picked the rand crate for a simple example. Adding to the manifest:

[dependencies]
rand = "0.7"

Running cargo installs the dependency and builds the updated project (which exercises some basic random capabilities):

$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.02s
     Running `target/debug/helloc`
Using the rand crate
--------------------
Random unsigned 8-bit number: 47
Random boolean: true
Random choice of direction: ⬋
Unshuffled numbers: [1, 2, 3, 4, 5]
Shuffled: [2, 4, 5, 1, 3]

Credits and References

About LCK#115 rustcargo
Project Source on GitHub Return to the Project Catalog

This page is a web-friendly rendering of my project notes shared in the LittleCodingKata GitHub repository.

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.