Menu
CoddyTech

Shared Borrows

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

In JavaScript, assigning an array or object to another variable copies the reference, not the data. Every alias points at the same storage, and any of them may push, sort or overwrite it at any moment. const only stops a name from being rebound; it does not protect the contents. Object.freeze does lock an object at runtime, but the lock is shallow and applies to everyone, including the code that created it. Rust &T is a shared borrow: a read-only view of a value that someone else owns. Any number of shared borrows may coexist, and while one is still in use, ordinary mutation of that value is rejected at compile time, even through the owner. Borrowing does not transfer ownership, so the owner remains responsible for dropping the value. The examples read one list of readings through two views of the same storage. A function that takes &[i32] works the same way: it can read the caller's numbers, but it cannot change or consume them. Types built for interior mutability can allow controlled changes through a shared reference; a plain vector has no such mechanism.

Complete standalone JavaScript program:

const readings = [4, 9, 2];
const first = readings;
const second = readings;
console.log(first.length, second[1], first === second);

JavaScript output:

3 9 true

Complete standalone Rust program:

fn main() {
    let readings = vec![4, 9, 2];
    let first = &readings;
    let second = &readings;
    println!("{} {} {}", first.len(), second[1], std::ptr::eq(first, second));
}

Rust output:

3 9 true
challenge icon

Challenge

Easy

Implement pub fn spread(values: &[i32]) -> i32 and pub fn total(values: &[i32]) -> i32 in readings.rs. spread is maximum minus minimum, or zero for an empty slice; total is the sum, also zero when empty. Neither function changes or consumes the caller's collection. solve reads whitespace-separated integers and returns spread:total. There are at most 100 numbers, each from -1000 to 1000. Both APIs must accept arbitrary subslices and repeated calls.

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, readings.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 readings;
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 data = vec![41, -8, 13, -8, 99];
assert_eq!(readings::spread(&data[1..4]), 21);
assert_eq!(readings::total(&data[1..4]), -3);
assert_eq!(readings::spread(&[]), 0);
assert_eq!(readings::total(&[]), 0);
assert_eq!(readings::spread(&data[2..3]), 0);
assert_eq!(readings::total(&data), 137);
assert_eq!(data, vec![41, -8, 13, -8, 99]);

    // 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