Lifetimes and Views
Lesson 19 of 48 in Coddy's Rust for JavaScript Developers course.
In JavaScript, a reference keeps whatever it points at alive: the garbage collector frees an object or string only when nothing can reach it any more. A function may return anything it likes, including a value it created locally, and the caller never has to think about how long it lasts. Rust references do not keep an owner alive. A lifetime parameter such as 'a states how a returned borrow relates to the borrowed inputs; it does not allocate memory, extend an owner or schedule cleanup. The Rust function below returns a slice of its input, so its signature says the result borrows from text and may be used only while that text is alive. The JavaScript slice call produces a new string value instead, and nothing ties it to the original. When a function has two borrowed inputs and may return either, giving both the same lifetime limits the result to the region where both are valid. A Rust function can never return a reference to a local String it built, because that string is dropped when the function returns. Return an owned String when the caller needs independent text.
Complete standalone JavaScript program:
function firstWord(text) {
const end = text.indexOf(" ");
return end === -1 ? text : text.slice(0, end);
}
console.log(firstWord("amber violet"));
JavaScript output:
amber
Complete standalone Rust program:
fn first_word<'a>(text: &'a str) -> &'a str {
match text.find(' ') {
Some(end) => &text[..end],
None => text,
}
}
fn main() {
let line = String::from("amber violet");
println!("{}", first_word(&line));
}
Rust output:
amber
Challenge
EasyImplement pub fn before<'a>(text: &'a str, delimiter: char) -> &'a str in views.rs. Return a borrowed prefix before the first delimiter, excluding that delimiter. If absent, return the entire input; a leading delimiter yields an empty slice. Support any Unicode delimiter and text without copying to an owned string. The input's first line is exactly one delimiter character; its second line is text, which may be empty. solve returns the prefix. Input text has no embedded newline. The result must borrow the input storage.
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, views.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 views;
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 text = String::from("α/β/γ");
let found = views::before(&text, '/');
assert_eq!(found, "α");
assert_eq!(found.as_ptr(), text.as_ptr());
assert_eq!(views::before(&text, 'β'), "α/");
assert_eq!(views::before(&text, '!'), text.as_str());
assert_eq!(views::before("", ':'), "");
assert_eq!(views::before("/tail", '/'), "");
// 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 JavaScript 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