Menu
CoddyTech

Methods and Receivers

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

A C# instance method receives a managed object reference as this; its signature usually does not state whether it reads, mutates, or consumes the object. Rust makes that choice visible in the receiver. &self borrows for shared access, &mut self borrows exclusively for mutation, and self takes the value by ownership. The banner below exposes all three: a view, an ASCII uppercase update, and conversion into owned bytes. After the consuming conversion, the banner cannot be used again. The C# method that returns encoded bytes does not consume its instance; it remains callable through aliases. A consuming method is useful when ownership should move into a result or a state transition should prevent reuse. Receiver syntax does not prove arbitrary business invariants, but it gives the compiler enforceable access and ownership information. This example transforms text rather than accumulating numeric state.

Complete C# program:

using System;
using System.Text;
class Banner {
    private string text;
    public Banner(string value) { text = value; }
    public string View() { return text; }
    public void Uppercase() { text = text.ToUpperInvariant(); }
    public byte[] ToBytes() { return Encoding.UTF8.GetBytes(text); }
}
class Program {
    static void Main() {
        var banner = new Banner("go");
        Console.WriteLine(banner.View());
        banner.Uppercase();
        Console.WriteLine(banner.ToBytes()[0]);
    }
}

Complete Rust program:

struct Banner { text: String }
impl Banner {
    fn view(&self) -> &str { &self.text }
    fn uppercase(&mut self) { self.text.make_ascii_uppercase(); }
    fn into_bytes(self) -> Vec<u8> { self.text.into_bytes() }
}
fn main() {
    let mut banner = Banner { text: String::from("go") };
    println!("{}", banner.view());
    banner.uppercase();
    println!("{}", banner.into_bytes()[0]);
}
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 C# Developers

Practice on your own: Online Rust compiler