Rust Lesson 4: Structs and Enums

Rust Lesson 4: Structs and Enums featured illustration

πŸ“Ž This article includes 1 downloadable practice file ↓

⏱ 1 min read

πŸ“˜ Rust Beginner Course Β· Lesson 4 of 6

Advertisement
struct Line { item: String, qty: u32, rate: f64 }
impl Line { fn amount(&self) -> f64 { self.qty as f64 * self.rate } }

enum Status { Paid, Pending { days: u32 }, Cancelled }
fn label(s: &Status) -> String {
    match s {
        Status::Paid => "Paid".into(),
        Status::Pending { days } => format!("Pending {days} days"),
        Status::Cancelled => "Cancelled".into(),
    }
}

match must cover every variant, so adding a new status forces you to handle it everywhere. The project file uses an enum for row errors.

Code for this course follows standard, current syntax; we test JavaScript and PowerShell scripts before publishing, and R/Java/Rust examples are kept to core language features. Tell us if anything fails on your setup.

Practice

Add the Line struct and Status enum to a project and print labels.

Advertisement

πŸ“Ž Practice files for this article

Free to use for learning. Files with macros (.bas) are plain text β€” import them with Alt+F11 β†’ File β†’ Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong

Leave a Comment