首页 > 解决方案 > Rust 生命周期 - 书籍示例解决方案

问题描述

在 Rust Book 上有这个生命周期的例子:

struct Foo<'a> {
    x: &'a i32,
}

fn main() {
    let x;                    // -+ x goes into scope
                              //  |
    {                         //  |
        let y = &5;           // ---+ y goes into scope
        let f = Foo { x: y }; // ---+ f goes into scope
        x = &f.x;             //  | | error here
    }                         // ---+ f and y go out of scope
                              //  |
    println!("{}", x);        //  |
}   

将其简化为:

fn main() {
    let x;
    {
        let y = 42;
        x = &y;
    }

    println!("The value of 'x' is {}.", x);
}

没有它是否可以工作clone

标签: rustlifetime

解决方案


在此示例中,您可以y通过删除花括号引入的范围来简单地延长 的生命周期。

fn main() {
    let x;

    let y = 42;
    x = &y;

    println!("The value of 'x' is {}.", x);
}

或者,正如其他人建议的那样,您可以通过从 中删除引用运算符来将所有权从 转移yx,即将值从转移y到:x&y

fn main() {
    let x;
    {
        let y = 42;
        x = y;
    }

    println!("The value of 'x' is {}.", x);
}

推荐阅读