Menu
CoddyTech

Structs and Fields

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

Java combines state and methods inside a class declaration. Rust declares named fields in a struct, then places methods in a separate impl block. A struct value is not automatically a heap object behind a reference. It can be owned directly by a local variable, moved into another value, or stored behind an explicit pointer type such as Box.

Field access uses a dot in both languages. Rust struct construction names the fields, so it does not require a constructor method to exist. Fields are private by default outside their module; pub exposes individual fields. Privacy is a module rule, not exactly Java private-to-class access. The example has a text label and a boolean flag, showing field reads without implementing an arithmetic model for the challenge.

Java: complete program

class Main {
    static class Lamp {
        String label; boolean on;
        Lamp(String label, boolean on) { this.label = label; this.on = on; }
    }
    public static void main(String[] args) {
        Lamp lamp = new Lamp("desk", true);
        System.out.println(lamp.label + ":" + lamp.on);
    }
}

Rust: complete program

struct Lamp { label: String, on: bool }
fn main() {
    let lamp = Lamp { label: String::from("desk"), on: true };
    println!("{}:{}", lamp.label, lamp.on);
}

Pitfall: writing a Rust struct does not imply Java inheritance, a hidden superclass, or automatic reference sharing.

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 Java Developers

Practice on your own: Online Rust compiler