Skip to content
On this page

生命周期3:exercises/lifetimes/lifetimes3.rs

题目

rust
// lifetimes3.rs
//
// Lifetimes are also needed when structs hold references.
//
// Execute `rustlings hint lifetimes3` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

struct Book {
    author: &str,
    title: &str,
}

fn main() {
    let name = String::from("Jill Smith");
    let title = String::from("Fish Flying");
    let book = Book { author: &name, title: &title };

    println!("{} by {}", book.title, book.author);
}

当结构体保存引用的时候,也需要生命周期。

题目解析

rust
struct Book { 
    author: &str, 
    title: &str, 
} 
struct Book<'a> { 
    author: &'a str, 
    title: &'a str, 
} 

参考资料

Powered by VitePress