Menu
CoddyTech

Mutable Borrows

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

Swift inout permits a function to update caller state and requires exclusive access for the duration of that call. Its semantic model is not a general-purpose stored Rust mutable reference. Rust &mut [i32] borrows a region under checked exclusivity, without transferring the vector owner or requiring a copy. The owner can be read again after the last conflicting mutable use. Both examples swap two positions and then observe the result. Disjoint regions can be borrowed separately when Rust can prove nonoverlap. Treat Swift access exclusivity and Rust lifetime-checked borrowing as related concerns with different type systems, rather than identical ampersand syntax.

Complete standalone Swift program:

func exchange(_ values: inout [Int]) {
    values.swapAt(0, 1)
}
var values = [2, 9]
exchange(&values)
print("\(values[0]) \(values[1])")

Swift output:

9 2

Complete standalone Rust 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]);
}

Rust output:

9 2
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 Swift Developers

Practice on your own: Online Rust compiler