Methods and Receivers
Lesson 32 of 48 in Coddy's Rust for C++ Developers course.
C++ uses an implicit object parameter, with const and ref qualifiers controlling which methods can be called. Rust spells the receiver as &self, &mut self, or self. These mean shared borrowing, exclusive borrowing, and ownership transfer respectively. A C++ rvalue-qualified member can move a field from its object, but calling it does not make the original variable statically inaccessible; the object's resulting state still follows its class contract. A Rust method consuming a non-copy owner prevents later use of the moved owner. Observers should borrow when they do not need ownership. Mutation should be explicit, and consuming methods can return owned components. The examples toggle a door and extract its text, with no arithmetic accumulation from the exercise.
Complete standalone C++17 program:
#include <iostream>
#include <string>
#include <utility>
class Door {
bool open_ = false;
std::string label_ = "west";
public:
bool is_open() const { return open_; }
void toggle() { open_ = !open_; }
std::string take_label() && { return std::move(label_); }
};
int main() {
Door d; d.toggle(); bool state = d.is_open();
auto text = std::move(d).take_label();
std::cout << std::boolalpha << state << ' ' << text << '\n';
}Complete standalone Rust program:
struct Door { open: bool, label: String }
impl Door {
fn is_open(&self) -> bool { self.open }
fn toggle(&mut self) { self.open = !self.open; }
fn into_label(self) -> String { self.label }
}
fn main() {
let mut d = Door { open: false, label: "east".to_string() };
d.toggle();
let open = d.is_open();
println!("{} {}", open, d.into_label());
}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 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