Shared Borrows
Lesson 17 of 48 in Coddy's Rust for C# Developers course.
A Rust shared reference &T gives temporary access without transferring ownership. Multiple shared borrows may overlap. For ordinary values, the owner cannot be mutated or moved while such borrows are still used. C# passing a class reference to a method also avoids copying the object, but does not establish Rust's compile-time access restrictions. A string in C# is immutable by its API; this does not make all managed objects read-only when passed as parameters. The Rust helper accepts &str, a view of UTF-8 text, and tests a suffix. Two shared views refer to the same owned string and remain valid while used. A shared reference is not an unconditional claim of deep immutability: Rust has types with controlled interior mutability. These examples use ordinary strings and require no such mechanism. Borrowing is the appropriate API when the function only needs to inspect its input.
Complete C# program:
using System;
class Program {
static bool IsLog(string text) { return text.EndsWith(".log", StringComparison.Ordinal); }
static void Main() {
string path = "audit.log";
string left = path, right = path;
Console.WriteLine("{0} {1}", IsLog(left), IsLog(right));
}
}Complete Rust program:
fn is_log(text: &str) -> bool { text.ends_with(".log") }
fn main() {
let path = String::from("audit.log");
let left = &path;
let right = &path;
println!("{} {}", is_log(left), is_log(right));
}Challenge
EasyImplement 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));
}
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