Mutable Borrows
Lesson 18 of 48 in Coddy's Rust for C Developers course.
Use &mut T when a function must change its caller's value. The caller must own a mutable binding and pass &mut value. The reference itself grants exclusive access for the duration of its use: Rust rejects simultaneous conflicting shared or mutable borrows. Dereference a mutable reference with * to read or assign its target. A mutable slice can expose only part of a collection. Its methods, such as reverse(), change that existing region in place. After the borrow's final use, the owner can be used again. This encodes the aliasing discipline that C programmers otherwise document and enforce manually.
C
#include <stdio.h>
#include <stddef.h>
void reverse(int *p, size_t n) {
for (size_t i = 0; i < n / 2; ++i) {
int saved = p[i]; p[i] = p[n - 1 - i]; p[n - 1 - i] = saved;
}
}
int main(void) {
int data[] = {1, 2, 3, 4};
reverse(data + 1, 3);
printf("%d %d %d %d\n", data[0], data[1], data[2], data[3]);
return 0;
}Rust
fn reverse(values: &mut [i32]) { values.reverse(); }
fn main() {
let mut data = vec![1, 2, 3, 4];
reverse(&mut data[1..]);
println!("{} {} {} {}", data[0], data[1], data[2], data[3]);
}Making a local copied integer mutable does not change its source element. Mutate through the reference, or use a slice operation that writes into the borrowed storage.
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