Building a Crate with Cargo
Take the text-mocking programme from the previous chapter and reorganise it as a reusable Rust library with a small executable. Discover how Cargo, modules and public APIs replace the need for a single increasingly large source file.
Practical Checklist
1. Packages, crates and Cargo
A package is described by Cargo.toml and can contain a library crate and one or more binary crates. A crate is a Rust compilation unit. In this practical, src/lib.rs is the library crate root and src/main.rs is the executable crate root.
| Item | Role |
|---|---|
Cargo.toml | Package metadata and dependency declarations |
src/main.rs | Entry point of the binary crate |
src/lib.rs | Root of the reusable library crate |
src/message.rs | Module containing the text-mocking implementation |
target/ | Generated build artefacts |
-
Create the new package on the BeagleBone. Use a new directory; do not overwrite the earlier
~/rust/first_program/main.rs.cd ~/rust cargo new text_mocker cd text_mocker -
Inspect the generated files.
ls -la cat Cargo.toml cat src/main.rsYou should see a
[package]section inCargo.tomland amain.rscontaining a simplefn main(). -
Build and run the generated programme without network access.
cargo build --offline cargo run --offlineCargo chooses the appropriate native target automatically when running on the BeagleBone. You can also use
cargo check --offlinefor fast compile-time analysis without producing a final executable.
2. Create a library crate
-
Create
src/lib.rsandsrc/message.rs:touch src/lib.rs src/message.rs -
Add the following to
src/lib.rs:#![allow(unused)] fn main() { pub mod message; }mod message;tells Rust to load the module fromsrc/message.rs. Thepubkeyword makes this module accessible to code outside the library crate, such as your binary crate. -
Add the reusable implementation to
src/message.rs:#![allow(unused)] fn main() { pub struct TextMocker { text: String, } impl TextMocker { pub fn new(text: &str) -> Self { Self { text: String::from(text) } } } pub trait Transform { fn transform(&self) -> String; } impl Transform for TextMocker { fn transform(&self) -> String { let mut result = String::new(); for (index, character) in self.text.chars().enumerate() { if index % 2 == 0 { result.push(character.to_ascii_lowercase()); } else { result.push(character.to_ascii_uppercase()); } } result } } }The
textfield stays private. Consumers construct aTextMockerusingTextMocker::new()rather than modifying its internal data directly.
3. Access modules using use
-
Replace
src/main.rswith:use text_mocker::message::{TextMocker, Transform}; fn main() { let message = TextMocker::new("Hello"); println!("{}", message.transform()); }Here
text_mockeris the library crate name,messageis its public module, andusebringsTextMockerandTransforminto scope. The trait must be in scope for the method-call syntax shown here. -
Check, build and run:
cargo check --offline cargo build --offline cargo run --offlineExpected output:
hElLo
4. Explore pub and compiler diagnostics
-
Temporarily remove
pubfrompub mod message;insidesrc/lib.rs, then run:cargo check --offlineObserve that the binary crate can no longer access the private
messagemodule. -
Restore
pub mod message;. Next, temporarily removepubfrompub fn newinsidesrc/message.rsand check again. Explain why the constructor becomes inaccessible across the crate boundary. -
Restore the working version and check it once more.
cargo check --offline
5. Add tests with the standard library
-
At the bottom of
src/message.rs, add this test module:#![allow(unused)] fn main() { #[cfg(test)] mod tests { use super::{TextMocker, Transform}; #[test] fn alternating_case() { let mocker = TextMocker::new("Hello"); assert_eq!(mocker.transform(), "hElLo"); } #[test] fn empty_input() { let mocker = TextMocker::new(""); assert_eq!(mocker.transform(), ""); } } }#[cfg(test)]includes the test module only for test builds.use super::...imports items from its parent module, andassert_eq!checks expected behaviour. -
Run the tests offline:
cargo test --offlineBoth tests should pass. Temporarily change an expected result to observe a failing assertion, then restore it.
6. Investigate the build outputs
-
View the source directory and build output:
ls -la src ls -la target/debugThe
target/debug/directory contains development build artefacts. The executable is generally located attarget/debug/text_mocker. -
Compile an optimised build:
cargo build --release --offline ls -la target/releaseCompare the development and release executables. They are both compiled for the BeagleBone's native architecture.
7. Independent exercise
Keep the new Shout implementation in the same message module. Import it in the binary using use text_mocker::message::{Shout, TextMocker, Transform};. Run cargo test --offline and cargo run --offline.
Add this to src/message.rs before the existing tests:
#![allow(unused)]
fn main() {
pub struct Shout {
text: String,
}
impl Shout {
pub fn new(text: &str) -> Self {
Self { text: String::from(text) }
}
}
impl Transform for Shout {
fn transform(&self) -> String {
self.text.to_ascii_uppercase()
}
}
}
Replace src/main.rs with:
use text_mocker::message::{Shout, TextMocker, Transform};
fn main() {
let mocker = TextMocker::new("Hello");
let shout = Shout::new("Hello");
println!("{}", mocker.transform());
println!("{}", shout.transform());
}
Add this test inside the existing tests module, alongside the previous two:
#![allow(unused)]
fn main() {
#[test]
fn shouting() {
let shout = super::Shout::new("Hello");
assert_eq!(shout.transform(), "HELLO");
}
}