Structs and Fields
Lesson 30 of 48 in Coddy's Rust for R Developers course.
R lists can group differently typed fields dynamically, and class attributes or formal object systems add other contracts when needed. Rust structs declare named fields and their types up front. Construction supplies those fields directly or through an explicit associated function; there is no automatic R-style class dispatch during a struct literal. Methods live in impl blocks and visibility follows modules. The examples store a name and boolean without requiring inheritance. Ordinary R lists have value semantics, while a Rust struct owning String normally moves on assignment. Use a map for dynamic keys and a struct for stable fields, and choose public representation deliberately.
R: complete program
theme <- list(name = "dusk", dark = TRUE)
cat(theme$name, "\n", tolower(as.character(theme$dark)), "\n", sep = "")
Rust: complete program
struct Theme { name: String, dark: bool }
fn main() {
let theme = Theme { name: String::from("dusk"), dark: true };
println!("{}", theme.name);
println!("{}", theme.dark);
}An existing Rust struct cannot acquire an undeclared field at runtime.
Challenge
EasyImplement parcel::Parcel with public unit_mass: i32 and count: i32 fields, and parcel::total(parcel: &Parcel) -> i32, returning their product without changing either field. In exercise::solve(input: &str) -> String, read zero or more whitespace-separated pairs of nonnegative integers, each at most 1000. Construct a parcel for each pair. Return one total per line, or empty when there are no pairs. Input always contains complete pairs.
Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.
Your code goes in exercise.rs, parcel.rs. main.rs holds the supplied input/output code and cannot be edited.
Try it yourself
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod parcel;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
let mut p = parcel::Parcel { unit_mass: 17, count: 13 };
assert_eq!(parcel::total(&p), 221);
assert_eq!(parcel::total(&p), 221);
p.count = 0;
assert_eq!(parcel::total(&p), 0);
assert_eq!(p.unit_mass, 17);
let q = parcel::Parcel { unit_mass: 0, count: 19 };
assert_eq!(parcel::total(&q), 0);
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for R Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap7Structs and State
Structs and FieldsImpl and ConstructorsMethods and ReceiversEncapsulationComposition and OwnershipReceipt State Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler