Structs and Fields
Lesson 30 of 48 in Coddy's Rust for JavaScript Developers course.
A JavaScript object literal needs no declaration: any object can have any properties, you can add more later, and reading a property that is not there, even one you misspelled, quietly gives undefined. Rust structs are named data types with declared fields. Construction names every field explicitly, leaving one out is a compile error, and reading a field that does not exist does not compile. Another struct with the same field shape is still a different type, so the two are not interchangeable. The examples represent a display preference and read its boolean field. A Rust struct does not need a constructor method when its fields are accessible; the literal Preference { compact: true } builds it directly. Methods live in separate impl blocks rather than on a prototype. Privacy comes from modules and field visibility: a field marked pub can be read from outside its module. Decide whether a field belongs in the public API before exposing it, because callers can depend on public representation.
Complete standalone JavaScript program:
const preference = { compact: true };
console.log(preference.compact);
console.log(preference.compcat);
JavaScript output:
true
undefined
Complete standalone Rust program:
struct Preference { compact: bool }
fn main() {
let preference = Preference { compact: true };
println!("{}", preference.compact);
}
Rust output:
true
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 JavaScript 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