Menu
CoddyTech

Methods and Receivers

Lesson 32 of 48 in Coddy's Rust for Java Developers course.

Java instance methods receive an implicit this reference. Java has no ordinary method signature that makes the caller's local object reference unusable after a call. Rust receiver forms state the access contract: &self borrows shared access, &mut self borrows exclusive mutable access, and self takes ownership. A consuming method can transfer owned fields out of the value.

The example defines only a consuming extraction method. It returns the string stored in a capsule. Calling it moves the capsule, so the caller can use the returned string but cannot use the old capsule as an intact value. This rule does not mean every self receiver must destroy the data; here the data survives under its new owner. Java's analogous method returns a reference but leaves the object reference usable.

Java: complete program

class Main {
    static class Capsule {
        final String text;
        Capsule(String text) { this.text = text; }
        String intoText() { return text; }
    }
    public static void main(String[] args) {
        Capsule capsule = new Capsule("sealed");
        String text = capsule.intoText();
        System.out.println(text + ":" + capsule.text);
    }
}

Rust: complete program

struct Capsule { text: String }
impl Capsule { fn into_text(self) -> String { self.text } }
fn main() {
    let capsule = Capsule { text: String::from("sealed") };
    let text = capsule.into_text();
    println!("{}", text);
}

Pitfall: a Rust consuming method is more than a naming convention like Java finish; the receiver type enforces ownership transfer.

challenge icon

Challenge

Easy

Implement 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));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for Java Developers

Practice on your own: Online Rust compiler