Structs and Fields
Lesson 30 of 48 in Coddy's Rust for C Developers course.
A Rust struct names a record layout, much like a C struct. Construct it with named fields, then read fields through a value or a reference using the same dot syntax. Rust has no separate -> field operator. A type and its fields have separate visibility: exporting the type does not automatically export every field. This example moves a point horizontally through a mutable reference. The original point changes because the function borrows the same record.
C
#include <stdio.h>
struct Point { int x; int y; };
void shift(struct Point *p, int dx) { p->x += dx; }
int main(void) {
struct Point p = {2, 5};
shift(&p, 4);
printf("%d %d\n", p.x, p.y);
return 0;
}Rust
struct Point { x: i32, y: i32 }
fn shift(p: &mut Point, dx: i32) { p.x += dx; }
fn main() {
let mut p = Point { x: 2, y: 5 };
shift(&mut p, 4);
println!("{} {}", p.x, p.y);
}C member access through a pointer uses p->x; Rust automatically dereferences p.x. A mutable borrow must be explicit at the call site as &mut p.
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 C 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