是否有用于构造包含临时引用的结构的单行语法? [英] Is there one-line syntax for constructing a struct that contains a reference to a temporary?

查看:52
本文介绍了是否有用于构造包含临时引用的结构的单行语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下无效的 Rust 代码.有一个结构 Foo 包含对第二个结构 Bar 的引用:

Consider the following invalid Rust code. There is one struct Foo that contains a reference to a second struct Bar:

struct Foo<'a> {
    bar: &'a Bar,
}

impl<'a> Foo<'a> {
    fn new(bar: &'a Bar) -> Foo<'a> {
        Foo { bar }
    }
}

struct Bar {
    value: String,
}

impl Bar {
    fn empty() -> Bar {
        Bar {
            value: String::from("***"),
        }
    }
}

fn main() {
    let foo = Foo::new(&Bar::empty());
    println!("{}", foo.bar.value);
}

编译器不喜欢这样:

error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:24:25
   |
24 |     let foo = Foo::new(&Bar::empty());
   |                         ^^^^^^^^^^^^ - temporary value is freed at the end of this statement
   |                         |
   |                         creates a temporary which is freed while still in use
25 |     println!("{}", foo.bar.value);
   |                    ------------- borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

我可以按照编译器所说的去做——使用 let 绑定:

I can make it work by doing what the compiler says - using a let binding:

fn main() {
    let bar = &Bar::empty();
    let foo = Foo::new(bar);
    println!("{}", foo.bar.value);
}

然而,突然间我需要两行代码来完成一些像实例化我的 Foo 这样微不足道的事情.有没有简单的方法可以在单行中解决这个问题?

However, suddenly I need two lines for something as trivial as instantiating my Foo. Is there any simple way to fix this in a one-liner?

推荐答案

不,没有这样的语法,除了您输入的内容.

No, there is no such syntax, other than what you have typed.

有关参考临时临时文件的详细信息,请参阅:

For the details of how long a temporary lives when you take a reference to it, see:

将有一个父结构同时拥有 bar 和引用它的 foos.

There will be a parent struct owning both the bar and the foos referencing it.

祝你好运:

这篇关于是否有用于构造包含临时引用的结构的单行语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆