Menu
CoddyTech

Mutable Borrows

Lesson 18 of 48 in Coddy's Rust for JavaScript Developers course.

In JavaScript, any alias of an array can mutate it, in any order, with nothing checking who else is looking. A helper that receives an array can sort or overwrite it, and the caller sees the change because both names share one array. Rust &mut T also gives access to the original storage, but the access is exclusive: while a mutable borrow is in use, no other shared or mutable borrow of the same value may be used, and the owner itself cannot be read or written. The example reverses an array through a mutable reference and overwrites one element, then reads the owner. Rust ends a borrow at its last use rather than at the closing brace, so the final read is allowed. A mutable reference is not a copy; every change through it is visible in the original. The same holds for a function that takes &mut [i32]: it may edit the caller's elements in place, but only those inside the slice it was given. Exclusivity concerns overlapping storage, so disjoint parts of one array can be borrowed separately with suitable APIs.

Complete standalone JavaScript program:

const scores = [3, 5, 8];
const view = scores;
view.reverse();
view[0] = 0;
console.log(scores.join(","));

JavaScript output:

0,5,3

Complete standalone Rust program:

fn main() {
    let mut scores = [3, 5, 8];
    let view = &mut scores;
    view.reverse();
    view[0] = 0;
    println!("{},{},{}", scores[0], scores[1], scores[2]);
}

Rust output:

0,5,3
challenge icon

Challenge

Easy

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

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

All lessons in Rust for JavaScript Developers

Practice on your own: Online Rust compiler