Lifetimes and Views
Lesson 19 of 48 in Coddy's Rust for C Developers course.
A borrowed string slice &str is a UTF-8 view into someone else's storage. Returning such a view is safe only while that storage remains alive. A lifetime parameter such as 'a describes that relationship; it does not keep a value alive or allocate storage. In fn pick<'a>(left: &'a str, right: &'a str) -> &'a str, the result may come from either argument, so its usable lifetime is limited by both. A single borrowed input usually allows lifetime elision, but explicit annotations can document the connection. For Unicode-safe prefix boundaries, char_indices() yields each scalar and its starting byte offset; nth(n) selects the scalar after the first n scalars, when one exists. Never return a reference into a local String that is dropped on function exit. C can return a pointer into an array too, but the compiler generally cannot enforce its lifetime.
C
#include <stdio.h>
#include <string.h>
const char *shorter(const char *a, const char *b) {
return strlen(a) <= strlen(b) ? a : b;
}
int main(void) {
char a[] = "pear", b[] = "fig";
const char *view = shorter(a, b);
printf("%s %s\n", view, a);
return 0;
}Rust
fn shorter<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() <= b.len() { a } else { b }
}
fn main() {
let a = String::from("pear");
let b = String::from("fig");
let view = shorter(&a, &b);
println!("{} {}", view, a);
}Adding a lifetime annotation cannot repair a dangling reference. Change who owns the storage, or return an owned String instead.
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 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