Menu
CoddyTech

Lifetimes and Views

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

Java references keep their reachable objects available to the garbage collector. A Java method can return a reference to an object created inside the method because the returned reference keeps it reachable. Rust borrowing does not extend the lifetime of the owner. A reference must never outlive the storage it refers to. Returning a borrow of a local owned string would therefore be rejected.

A lifetime parameter describes a relationship between borrows. In fn echo<'a>(s: &'a str) -> &'a str, the result is valid only within a lifetime supported by the input borrow. The annotation does not allocate, copy, keep the input alive, or choose its destruction time. With one borrowed input, Rust can elide this particular annotation; it is written here to expose the relationship. When several borrowed inputs can supply a result, explicit relationships may be needed.

Java: complete program

class Main {
    static String echo(String text) { return text; }
    public static void main(String[] args) {
        String original = "maple";
        String view = echo(original);
        System.out.println(view);
    }
}

Rust: complete program

fn echo<'a>(text: &'a str) -> &'a str { text }
fn main() {
    let original = String::from("maple");
    let view = echo(&original);
    println!("{}", view);
}

Pitfall: adding 'static cannot make a borrow of a local allocation live forever. String literals can have static lifetime because their storage exists for the program.

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

Practice on your own: Online Rust compiler