Composition and Ownership
Lesson 34 of 48 in Coddy's Rust for C# Developers course.
C# using arranges deterministic calls to IDisposable.Dispose; garbage collection alone does not promise prompt resource cleanup. A containing disposable object must arrange disposal of its owned disposable fields. Rust normally drops owned fields automatically when their containing value is dropped. The resource example prints a release marker so scope behavior is visible. C# explicitly forwards disposal to its child; Rust needs only the child's Drop implementation, because the holder owns that field. This is composition: one object contains another, with no invented inheritance relationship. Drop is not garbage collection, and it is not guaranteed in every termination path, such as process abort. Do not call a Rust Drop::drop method directly; std::mem::drop can consume a value when early disposal is needed. Moving a holder transfers responsibility for its owned fields rather than cloning or independently disposing the children.
Complete C# program:
using System;
class Resource : IDisposable {
public void Dispose() { Console.WriteLine("release"); }
}
class Holder : IDisposable {
private readonly Resource child = new Resource();
public void Dispose() { child.Dispose(); }
}
class Program {
static void Main() {
using (var holder = new Holder()) { Console.WriteLine("work"); }
Console.WriteLine("after");
}
}Complete Rust program:
struct Resource;
impl Drop for Resource {
fn drop(&mut self) { println!("release"); }
}
struct Holder { _child: Resource }
fn main() {
{
let _holder = Holder { _child: Resource };
println!("work");
}
println!("after");
}Challenge
EasyImplement 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));
}
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