Derived Value Semantics
Lesson 40 of 48 in Coddy's Rust for JavaScript Developers course.
JavaScript compares objects with === by identity: two object literals with equal fields are still two different objects, and the language has no built-in deep equality operator. Assigning an object to another variable copies the reference, so a change made through one name shows through the other, and spread syntax such as {...first} copies only the top level. Rust can derive value equality for a struct whose fields support it. Deriving Copy makes assignment duplicate the whole value implicitly, but only when every field can be copied; an owned String prevents this derive. Clone is an explicit duplication operation and may allocate for owned containers. The examples build two equal flags, then change a second binding of the first. JavaScript reports the flags unequal and sees the change through both names; Rust compares the stored fields and changes only the copy. Derives generate specific trait implementations, not runtime reflection. Choose only the semantics your domain needs; when a key uses equality and hashing, those implementations must agree.
Complete standalone JavaScript program:
const first = { enabled: true };
const second = { enabled: true };
const alias = first;
alias.enabled = false;
console.log(first === second);
console.log(first.enabled, alias.enabled);
JavaScript output:
false
false false
Complete standalone Rust program:
#[derive(Copy, Clone, PartialEq)]
struct Flag { enabled: bool }
fn main() {
let first = Flag { enabled: true };
let second = Flag { enabled: true };
let mut copy = first;
copy.enabled = false;
println!("{}", first == second);
println!("{} {}", first.enabled, copy.enabled);
}
Rust output:
true
true false
Challenge
EasyIn key.rs, define Key with public row: i32 and column: i32 fields and derive Copy, Clone, Debug, PartialEq, Eq, and Hash. Equality and hashing must use both fields. The derived debug representation is Key { row: n, column: n }. Implement unique::count(keys: &[Key]) -> usize, returning the number of distinct coordinate pairs without modifying the input. solve reads complete whitespace-separated integer pairs, each integer between -1000 and 1000. Return the distinct-pair count; empty input returns 0.
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, key.rs, unique.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 key;
mod unique;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
use std::collections::HashSet;
let a = key::Key { row: 13, column: -6 }; let mut b = a; b.column = 7;
assert_eq!(a.column, -6); assert_ne!(a, b); assert_eq!(a, a.clone());
assert_eq!(format!("{:?}", a), "Key { row: 13, column: -6 }");
let c = key::Key { row: 14, column: -6 };
let mut set = HashSet::new(); set.insert(a); set.insert(a.clone()); set.insert(b); set.insert(c);
assert_eq!(set.len(), 3);
assert_eq!(unique::count(&[a, b, c, a, b]), 3);
assert_eq!(unique::count(&[]), 0); assert_eq!(unique::count(&[a, a]), 1);
assert_eq!(unique::count(&[c, a]), 2);
// 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 JavaScript 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 Recap2Decisions and Loops
Boolean ConditionsIf ExpressionsMatch and EnumsLoops and RangesRecap: Charge Gate8Traits and Generic Code
Traits and ContractsGenerics and BoundsTrait ObjectsFunction PointersDerived Value SemanticsTesting Public ContractsScoring Contracts Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler