Alexander Yurchenko

Rust basics for PHP developers: Cargo, types, and functions

Created
Updated
Author
Alexander Yurchenko

Add up the priorities of several support tickets and compare the total with a threshold. The function signature shows what it accepts and what it returns.

Create a demo project

PHP projects typically use Composer for dependencies. Cargo also resolves dependencies, and it manages builds and tests. The Cargo.toml manifest describes the package, its language edition, and its dependencies. The generated Cargo.lock records the selected versions. Commit it for an application to reproduce dependency selections, much as you would with composer.lock. The Cargo guide explains the package layout and manifest.

Open a terminal in a working directory outside the site and the application from the introduction. These commands create a fresh rust-foundations-demo directory with a src/main.rs file and move into it. Pick a working directory where that name is available.

BASH
# Check the tool versions
rustc --version
cargo --version
cargo new rust-foundations-demo --bin --vcs none
cd rust-foundations-demo

An edition is a language compatibility mode. cargo new writes the latest stable edition available to that version of Cargo into Cargo.toml. The tested toolchain writes edition = "2024". The compiler version is separate, and the same compiler also supports earlier editions. See the official edition guide.

What the types tell you

Rust checks types before a program runs. A function signature declares its parameter and return types. For a local binding such as urgent, the compiler can often infer the type from the expression. See the chapter on types and expressions.

  • let creates a binding that is immutable by default. With mut, the program can add priorities with push or update the total in the loop.
  • u32 is an unsigned 32-bit integer. Its range is sufficient for the small priorities in this example. When summing arbitrary input, decide how to handle overflow.
  • bool holds true or false. Here it holds the result of comparing the total with the threshold.
  • String owns a growable UTF-8 buffer. &str gives borrowed access to string data. The literal "support" is an &str, and String::from creates an owned string from it.
  • Vec<T> is a growable sequence whose elements share a type. A PHP array is an ordered map that can hold values of different types. The function takes an &[u32], a borrowed slice you can obtain from either a vector or a Rust array.

Read the function and run the program

Replace the entire contents of src/main.rs. The for loop in priority_total iterates over references to the slice elements, and *value reads the integer through its reference. The final expression total becomes the return value because it has no semicolon. The println! macro formats the output and adds a newline.

RUST
// A slice lets callers pass arrays or vectors without giving up ownership.
fn priority_total(values: &[u32]) -> u32 {
    let mut total = 0;
    for value in values {
        total += *value;
    }
    total
}

fn main() {
    let label = String::from("support");
    let mut priorities = vec![2_u32, 3];
    priorities.push(1);
    let urgent = priority_total(&priorities) >= 5;
    println!("{}: {}, urgent={}", label, priority_total(&priorities), urgent);
}

#[cfg(test)]
mod tests {
    use super::priority_total;

    #[test]
    fn totals_small_priorities() {
        assert_eq!(priority_total(&[2, 3, 1]), 6);
        // An empty slice leaves the initial total unchanged.
        assert_eq!(priority_total(&[]), 0);
    }
}

Run these commands from rust-foundations-demo:

BASH
cargo check
cargo build
cargo run
cargo test

  • cargo check checks the code without producing the final executable.
  • cargo build builds the executable.
  • cargo run builds the program as needed and runs it.
  • cargo test runs the tests. This program has one test that checks an ordinary slice and an empty slice.

The program prints:

TEXT
support: 6, urgent=true

Summary

Taking a slice lets the function work with more than one kind of collection. In the lesson on structs and error handling, types will describe the ticket itself and the possible outcomes of processing it.