Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Last updated: Friday 13 November 2026 @ 17:29:40
BeagleBone Black · Rust

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.

CargoCratesModulesVisibilityTesting
Practical Checklist
Chapter checklist 0 / 9 completed

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.

ItemRole
Cargo.tomlPackage metadata and dependency declarations
src/main.rsEntry point of the binary crate
src/lib.rsRoot of the reusable library crate
src/message.rsModule containing the text-mocking implementation
target/Generated build artefacts
  1. 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
  2. Inspect the generated files.

    ls -la
    cat Cargo.toml
    cat src/main.rs

    You should see a [package] section in Cargo.toml and a main.rs containing a simple fn main().

  3. Build and run the generated programme without network access.

    cargo build --offline
    cargo run --offline

    Cargo chooses the appropriate native target automatically when running on the BeagleBone. You can also use cargo check --offline for fast compile-time analysis without producing a final executable.

2. Create a library crate

  1. Create src/lib.rs and src/message.rs:

    touch src/lib.rs src/message.rs
  2. Add the following to src/lib.rs:

    #![allow(unused)]
    fn main() {
    pub mod message;
    }

    mod message; tells Rust to load the module from src/message.rs. The pub keyword makes this module accessible to code outside the library crate, such as your binary crate.

  3. 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 text field stays private. Consumers construct a TextMocker using TextMocker::new() rather than modifying its internal data directly.

3. Access modules using use

  1. Replace src/main.rs with:

    use text_mocker::message::{TextMocker, Transform};
    
    fn main() {
        let message = TextMocker::new("Hello");
        println!("{}", message.transform());
    }

    Here text_mocker is the library crate name, message is its public module, and use brings TextMocker and Transform into scope. The trait must be in scope for the method-call syntax shown here.

  2. Check, build and run:

    cargo check --offline
    cargo build --offline
    cargo run --offline

    Expected output:

    hElLo

4. Explore pub and compiler diagnostics

  1. Temporarily remove pub from pub mod message; inside src/lib.rs, then run:

    cargo check --offline

    Observe that the binary crate can no longer access the private message module.

  2. Restore pub mod message;. Next, temporarily remove pub from pub fn new inside src/message.rs and check again. Explain why the constructor becomes inaccessible across the crate boundary.

  3. Restore the working version and check it once more.

    cargo check --offline

5. Add tests with the standard library

  1. 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, and assert_eq! checks expected behaviour.

  2. Run the tests offline:

    cargo test --offline

    Both tests should pass. Temporarily change an expected result to observe a failing assertion, then restore it.

6. Investigate the build outputs

  1. View the source directory and build output:

    ls -la src
    ls -la target/debug

    The target/debug/ directory contains development build artefacts. The executable is generally located at target/debug/text_mocker.

  2. Compile an optimised build:

    cargo build --release --offline
    ls -la target/release

    Compare 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");
}
}