Structs and Fields
Lesson 30 of 48 in Coddy's Rust for C++ Developers course.
C++ aggregates can be initialized with positional brace syntax, and their fields may be public without accessors. Rust named structs construct values using field names, reducing dependence on field order. Struct fields are private to their defining module unless marked public, even when the struct itself is public. Borrowing a struct permits a helper to inspect or mutate it according to the reference kind. Owning a Rust struct does not automatically make it copyable; eligibility depends on its fields and its trait implementations. A struct containing an owned string commonly moves as a value. These examples use a small point to isolate field access and mutation. The exercise uses a different record and asks for a derived value without changing its fields.
Complete standalone C++17 program:
#include <iostream>
struct Position { int x; int y; };
void translate(Position& p, int dy) { p.y += dy; }
int main() {
Position p{2, 5}; translate(p, 3);
std::cout << p.x << ' ' << p.y << '\n';
}Complete standalone Rust program:
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);
}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