Menu
CoddyTech

Lifetimes and Views

Lesson 19 of 48 in Coddy's Rust for Dart Developers course.

Returning a Dart String reference keeps that immutable object reachable; no lifetime parameter ties the return value to the caller's variables. A Rust function returning one of two borrowed strings must state the relationship between input and output lifetimes. The annotation does not extend either owner's life or create a copy. It tells the checker how long the returned reference may safely be used. In these examples the false condition selects violet. A Rust function cannot return a borrow into its own newly created local String after that owner is dropped. Return an owned String when the function creates text that must escape, or borrow data whose owner already lives long enough.

Complete standalone Dart program:

String choose(String first, String second, bool useFirst) =>
    useFirst ? first : second;
void main() { print(choose('amber', 'violet', false)); }

Dart output:

violet

Complete standalone Rust program:

fn choose<'a>(first: &'a str, second: &'a str, use_first: bool) -> &'a str {
    if use_first { first } else { second }
}
fn main() {
    let first = String::from("amber");
    let second = String::from("violet");
    println!("{}", choose(&first, &second, false));
}

Rust output:

violet
challenge icon

Challenge

Easy

Implement 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));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for Dart Developers

Practice on your own: Online Rust compiler