Menu
CoddyTech

Shared Borrows

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

A shared reference &T permits reading without transferring ownership. Several shared references can coexist. A slice &[T] carries a pointer and a length, unlike a bare C pointer; bounds checking applies to indexing. Taking &values[1..3] borrows only that range, with the end excluded. Functions should accept a slice when they only need elements, because callers can pass arrays, vectors or subslices. Iterating with for &value in values copies each i32; the collection remains owned by the caller. While a shared borrow is still used, conflicting mutation is rejected. Prefer references to reproducing C pointer arithmetic.

C

#include <stdio.h>
#include <stddef.h>
size_t zeros(const int *values, size_t count) {
    size_t found = 0;
    for (size_t i = 0; i < count; ++i) if (values[i] == 0) ++found;
    return found;
}
int main(void) {
    int values[] = {0, 7, 0, 0};
    printf("%zu %d\n", zeros(values + 1, 2), values[0]);
    return 0;
}

Rust

fn zeros(values: &[i32]) -> usize {
    let mut found = 0;
    for &value in values { if value == 0 { found += 1; } }
    found
}
fn main() {
    let values = vec![0, 7, 0, 0];
    println!("{} {}", zeros(&values[1..3]), values[0]);
}

A slice does not allocate a new array and does not own the underlying storage. Its length is the selected range, not the full backing vector.

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 C Developers

Practice on your own: Online Rust compiler