保留另一个对象中参数的生命周期

时间:2016-12-21 01:09:03

标签: rust

我的结构X包含2个字段ownedrefed,用于保存insert函数传入的数字的所有权和引用。

fn main() {
    struct X<'a> {
        owned: Vec<i32>,
        refed: Vec<&'a i32>
    }

    impl<'a> X<'a> {
        fn insert(&mut self, n: i32) {
            self.owned.push(n);
            self.refed.push(&n);
        }
    }

    let mut x = X { owned: vec![], refed: vec![] };
    x.insert(1);
}

fiddle

当我运行它时,我收到以下错误:

error: `n` does not live long enough
  --> <anon>:10:30
   |
10 |             self.refed.push(&n);
   |                              ^ does not live long enough
11 |         }
   |         - borrowed value only lives until here
   |
   = note: borrowed value must be valid for the lifetime 'a as defined on unknown free region bounded by scope CodeExtent(36/CallSiteScope { fn_id: NodeId(24), body_id: NodeId(68) })...

error: aborting due to previous error

我很惊讶编译器认为n在函数结束后将不再可用,即使其所有权已经转移和扩展。那么我们如何解决这个问题?

0 个答案:

没有答案