Methods and Receivers
Lesson 32 of 48 in Coddy's Rust for JavaScript Developers course.
In JavaScript, a method written in a class body lives on the prototype, and this is whatever object the call goes through: envelope.open() sets this to envelope, while a detached const f = envelope.open; f() loses it. Nothing in the method says whether it only reads the object, changes it or uses it up, and the object stays reachable after every call. Rust receivers state that access in the signature: &self borrows for observation, &mut self borrows exclusively for mutation, and self takes ownership. The receiver is an ordinary first parameter, so it never comes loose the way this can. A consuming method can move owned fields into its return value. The examples open a wrapper and return its string. In Rust, the wrapper cannot be used afterward because open consumed it, while the JavaScript object could be opened again and again. Consumption is an API decision, not a request to free memory at once: the returned string lives on under its new owner. Choose a borrowed receiver when callers should keep using the same object.
Complete standalone JavaScript program:
class Envelope {
constructor(text) { this.text = text; }
open() { return this.text; }
}
const envelope = new Envelope("memo");
console.log(envelope.open());
JavaScript output:
memo
Complete standalone Rust program:
struct Envelope { text: String }
impl Envelope {
fn open(self) -> String { self.text }
}
fn main() {
let envelope = Envelope { text: "memo".to_string() };
println!("{}", envelope.open());
}
Rust output:
memo
Challenge
EasyImplement meter::Meter with private integer state. Meter::new(initial: i32) -> Meter stores the initial value. add(&mut self, delta: i32) adds a signed delta. value(&self) -> i32 reads without changing state. finish(self) -> i32 consumes the meter and returns its final value. solve reads an initial integer followed by zero or more deltas. Return the initial and every updated reading separated by single spaces, then a newline and final:n using the consuming method. All values and sums fit i32. Input always has an initial integer.
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, meter.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 meter;
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 a = meter::Meter::new(71); let b = meter::Meter::new(-21);
assert_eq!(a.value(), 71); a.add(-9); a.add(0); a.add(4);
assert_eq!(a.value(), 66); assert_eq!(a.value(), 66);
assert_eq!(b.value(), -21); assert_eq!(a.finish(), 66); assert_eq!(b.finish(), -21);
// 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 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