Mutable Borrows
Lesson 18 of 48 in Coddy's Rust for Ruby Developers course.
Ruby passes access to the same Array object, so changing its slots in a method is visible to the caller. Reassigning the method parameter to another array would instead change only that local binding. Rust &mut [i32] explicitly grants exclusive mutable access to the borrowed region without moving or cloning the vector. Conflicting shared and mutable uses cannot overlap, but disjoint regions can be borrowed independently when the compiler can prove separation. The owner becomes usable again once the conflicting borrow is no longer used. This is a compile-time access guarantee rather than Ruby ordinary shared-object mutation, and it applies to a place rather than limiting the entire program to one mutable reference.
Ruby: complete program
def exchange(values)
values[0], values[1] = values[1], values[0]
end
values = [2, 9]
exchange(values)
puts values.join(" ")
Rust: complete program
fn exchange(values: &mut [i32]) { values.swap(0, 1); }
fn main() {
let mut values = vec![2, 9];
let view = &mut values[..];
exchange(view);
println!("{} {}", values[0], values[1]);
}Mutating a referenced Ruby object differs from rebinding the method parameter.
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 Ruby 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