获得“借来的价值还不够长久"尝试将盒装 dyn 特性传递给函数时出错 [英] Getting "borrowed value does not live long enough" Error While Trying to Pass a Boxed dyn Trait into a Function

查看:51
本文介绍了获得“借来的价值还不够长久"尝试将盒装 dyn 特性传递给函数时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rust 的新手,我对借用检查器的行为感到非常困惑.

I'm new to rust and I get really confused by the behavior of the borrow checker.

trait Foo {
  fn foo(&self);
}

struct Bar<'a> {
  pub f : &'a Vec<i32>
}

impl<'a> Foo for Bar<'a> {
  fn foo(&self) {
    for i in self.f {
      println!("{}", i);
    }
  }
}

fn call(b : &Box<dyn Foo>) {
  b.foo();
}

fn main() {
  let a = vec!(1,2,3);
  let b : Box<dyn Foo> = Box::new(Bar {f : &a});
  call(&b)
}

通过编译这段代码,我得到:

By compiling this piece of code I get:

error[E0597]: `a` does not live long enough
  --> main.rs:23:44
   |
23 |   let b : Box<dyn Foo> = Box::new(Bar {f : &a});
   |                          ------------------^^--
   |                          |                 |
   |                          |                 borrowed value does not live long enough
   |                          cast requires that `a` is borrowed for `'static`
24 |   call(&b)
25 | }
   | - `a` dropped here while still borrowed

有人可以向我解释为什么在这种情况下 a 的寿命不够长吗?在我看来,它将贯穿程序的整个生命周期.

Could someone explain to me why in this case a does not live long enough? It seems to me that it will live through the entire life cycle of the program.

推荐答案

默认情况下,Box 的意思是Box,所以'static 值只能存储在 Box 中.a 是在函数内部创建的,因此它不适用于 'static.

By default, Box<dyn Foo> means Box<dyn Foo + 'static>, so only 'static values can be stored in Box<dyn Foo>. a is created inside a function, so it does not live for 'static.

您可以使用生命周期参数来调整生命周期:

You can adjust the lifetime by using a lifetime parameter:

fn call<'a>(b: &Box<dyn Foo + 'a>) {
    b.foo();
}

(playground)

这篇关于获得“借来的价值还不够长久"尝试将盒装 dyn 特性传递给函数时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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