Menu
CoddyTech

Composition and Ownership

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

Java composition usually stores references to member objects. A Rust struct can directly own another value as a field. Moving the outer value moves ownership of its owned fields; dropping it normally drops those fields as well. Rust has no class inheritance, so shared implementation is expressed through composition, traits and explicit delegation.

Resource cleanup also differs. Java garbage collection does not guarantee timely resource closure. AutoCloseable with try-with-resources provides deterministic closure on leaving the block. Rust Drop runs cleanup when an owned value is dropped, including ordinary scope exit. It is not a Java finalizer. Destructors should not be confused with a guarantee of cleanup after process abort, leaks or all shutdown situations. This example owns one marker, not a collection, and prints when its scope ends.

Java: complete program

class Main {
    static class Marker implements AutoCloseable {
        final String name = "open";
        public void close() { System.out.println("closed"); }
    }
    static class Envelope implements AutoCloseable {
        final Marker marker = new Marker();
        public void close() { marker.close(); }
    }
    public static void main(String[] args) {
        try (Envelope envelope = new Envelope()) {
            System.out.println(envelope.marker.name);
        }
    }
}

Rust: complete program

struct Marker { name: &'static str }
impl Drop for Marker { fn drop(&mut self) { println!("closed"); } }
struct Envelope { marker: Marker }
fn main() {
    {
        let envelope = Envelope { marker: Marker { name: "open" } };
        println!("{}", envelope.marker.name);
    }
}

Pitfall: a Java reference field does not establish Rust-style exclusive ownership, and GC alone is not the equivalent of Drop.

challenge icon

Challenge

Easy

Implement stop::Stop with public name: String and minutes: i32 fields. journey::Journey::new() -> Journey creates an empty owned collection. add(&mut self, stop: Stop) takes ownership and appends in arrival order. total(&self) -> i32 returns the sum of minutes without removing stops. finish(self) -> Vec<Stop> consumes the journey and returns every owned stop in order. solve reads complete name minutes pairs. Names have no whitespace; minutes are between 0 and 1000; there are at most 100 stops. Return total:n on the first line and the comma-separated stop names on the second, using empty for an empty journey.

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, stop.rs, journey.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 stop;
mod journey;
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 j = journey::Journey::new(); assert_eq!(j.total(), 0);
j.add(stop::Stop { name: "ridge".to_string(), minutes: 23 });
j.add(stop::Stop { name: "ridge".to_string(), minutes: 0 });
j.add(stop::Stop { name: "lake".to_string(), minutes: 8 });
assert_eq!(j.total(), 31); assert_eq!(j.total(), 31);
let out = j.finish(); assert_eq!(out.len(), 3);
assert_eq!((&out[0].name, out[0].minutes), (&"ridge".to_string(), 23));
assert_eq!((&out[1].name, out[1].minutes), (&"ridge".to_string(), 0));
assert_eq!((&out[2].name, out[2].minutes), (&"lake".to_string(), 8));
assert!(journey::Journey::new().finish().is_empty());
    // 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