Menu
CoddyTech

Structs and Fields

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

A C# struct is a value type, but copying it does not recursively copy objects referenced by its fields. The C# snapshot below contains an array reference and an integer. After copying the struct, changing the copied integer affects only the copy, while changing an array element is visible through both references. Rust structs group named fields but do not automatically implement Copy. The Rust snapshot owns a vector; its explicit derived Clone duplicates that vector's integer elements here. Modifying the clone therefore leaves the original vector unchanged. That behavior follows these field types, not a general promise that cloning any struct is deep. Public Rust fields permit direct access; private fields can enforce an API boundary. Construction names every required field unless a supported update form supplies the remainder. Avoid mapping all Rust structs to either C# classes or C# structs: ownership and implemented traits determine the semantics.

Complete C# program:

using System;
struct Snapshot { public int[] Codes; public int Version; }
class Program {
    static void Main() {
        var first = new Snapshot { Codes = new[] { 2 }, Version = 1 };
        var second = first;
        second.Codes[0] = 7;
        second.Version = 4;
        Console.WriteLine("{0} {1}", first.Codes[0], first.Version);
    }
}

Complete Rust program:

#[derive(Clone)]
struct Snapshot { codes: Vec<i32>, version: i32 }
fn main() {
    let first = Snapshot { codes: vec![2], version: 1 };
    let mut second = first.clone();
    second.codes[0] = 7;
    second.version = 4;
    println!("{} {}", first.codes[0], first.version);
}
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 C# Developers

Practice on your own: Online Rust compiler