Dependency Management
This page is under construction. Please come back later.
It is often easier to write programs when you don't have to write all the code from scratch. There are a large number of code libraries available, both open source (free) and commercial (paid). Using code libraries written by the community or commercial developers give you a leg up in your coding efforts by making a large library of useful functions and classes available to your program. All we need to do is manage these dependencies and include them in our programs.
Rust organizes code in to modules called "crates". All you need to do to use pre-written module is to download the .rs
Rust module file, put it in your project folder and then include it in your program.
An easier way is to use the [[Cargo]] software that comes with Rust to download and install libraries for you. The community maintains a large online library of crates that you can access using cargo
. Given the name of a module such as regex
and a version, you can add it to your cargo project configuration file "Cargo.toml" in one step from the command line:
Once added to your "Cargo.toml" file, the crate will be downloaded and installed next time you build and run your project with cargo.
- If you are on a Unix-like system, you can generally use
apt
to downloadcargo
if it is not on your system. - On MacOS you can install
cargo
using a Unix package manager like [[MacPorts]] or [[Homebrew]]. - On Windows you can install
cargo
using the [[Cygwin]] setup program.
You will want to download the [[Pure Programmer Rust Utils Crate]] which is needed by some examples and project. Simply put the "utils.rs" file in the same folder as your program. Then add a mod
or use
statement to the beginning of your source file depending on whether the crate is a source file in your directory like "utils.rs" or a crate downloaded and installed by cargo
:
The entire process of setting up a cargo
project takes just a few commands. The basic steps are:
- Create
cargo
empty project directory and files - Create "bin" directory in "src" directory
- Add source files and "utils.rs" to "bin" directory
- Add dependent crates using
cargo
- Build
cargo
- Run executable
Once setup you can use this project for all the examples and projects on this website. Just download source files and put them in the "src/bin" directory of the project. Be sure to use the name of the source file when you build and run the program.
If your Rust program doesn't use any crates or "utils.rs" you can simply use the Rust compiler rustc
to build your source file into an executable.
/****************************************************************************** * Simple first program. * * Copyright © 2020 Richard Lesh. All rights reserved. *****************************************************************************/ fn main() { println!("Hello, world!"); }
Output
References
- [[Rust Language Reference]]
- [[Rust Compiler]]