Menu
CoddyTech

Structs and Fields

Lesson 30 of 48 in Coddy's Rust for Python Developers course.

Python instances usually carry attributes dynamically, although classes can constrain this with mechanisms such as slots or properties. A Rust struct declares its fields and their types up front. A struct literal supplies each required field; it does not call an implicit Python-style initializer. Visibility is explicit, and methods are defined separately in an impl block. A struct containing an owned String owns that text, so assigning the struct normally moves it rather than producing another alias. The examples represent a display theme with a text name and a boolean. No inheritance hierarchy is required to describe this data.

Python: complete program

class Theme:
    def __init__(self, name, dark):
        self.name = name
        self.dark = dark
theme = Theme("dusk", True)
print(theme.name)
print(theme.dark)

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);
}

Rust does not allow adding an undeclared field to an existing struct instance at runtime.

challenge icon

Challenge

Easy

Implement 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));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for Python Developers

Practice on your own: Online Rust compiler