Mutable Borrows
Lesson 18 of 48 in Coddy's Rust for C# Developers course.
C# ref lets a method update the caller's variable. Rust &mut T also provides writable access, but adds an exclusivity rule: while an exclusive borrow is used, conflicting access to the same location is forbidden. This is not a rule that an entire function may contain only one mutable reference. Two independent variables can be borrowed mutably at the same time, as the Rust call to std::mem::swap shows. Rust can also recognize some disjoint parts of a value, and slice APIs can establish disjoint regions safely. The C# swap method receives two variable aliases; C# does not apply Rust's borrow checker to them. A mutable binding and a mutable borrow are related but distinct: the owner must permit mutation, then a temporary borrow grants access for the operation. After the call, both Rust owners are usable again.
Complete C# program:
using System;
class Program {
static void Swap(ref int a, ref int b) { int old = a; a = b; b = old; }
static void Main() {
int left = 4, right = 9;
Swap(ref left, ref right);
Console.WriteLine("{0} {1}", left, right);
}
}Complete Rust program:
fn main() {
let mut left = 4;
let mut right = 9;
std::mem::swap(&mut left, &mut right);
println!("{} {}", left, right);
}Challenge
EasyImplement pub fn cap(values: &mut [i32], ceiling: i32) -> usize in limits.rs. Replace each element strictly greater than ceiling by the ceiling and return the number of changed elements. Equal elements do not count. Empty slices return zero. Changes must be visible in the caller and restricted to the passed slice. Input has a ceiling followed by zero or more integers, all between -1000 and 1000. solve returns changed|values with values joined by commas; no values means the suffix after | is empty.
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, limits.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 limits;
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 data = vec![90, 4, 12, -3, 80];
assert_eq!(limits::cap(&mut data[1..4], 5), 1);
assert_eq!(data, vec![90, 4, 5, -3, 80]);
assert_eq!(limits::cap(&mut data[1..4], 5), 0);
assert_eq!(limits::cap(&mut [], -9), 0);
assert_eq!(limits::cap(&mut data[2..3], -4), 1);
assert_eq!(data[2], -4);
// 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 Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler