【问题标题】:Borrowed value does not live long enough when iterating over a generic value with a lifetime on the function body在函数体上有生命周期的泛型值上迭代时,借用值的生命周期不够长
【发布时间】:2019-04-28 08:40:35
【问题描述】:
fn func<'a, T>(arg: Vec<Box<T>>)
where
    String: From<&'a T>,
    T: 'a,
{
    let s: Vec<String> = arg.iter().map(|s| String::from(s)).collect();
    do_something_else(arg);
}

fn do_something_else<T>(arg: Vec<Box<T>>) {}

编译器抱怨arg 的寿命不够长。为什么呢?

error[E0597]: `arg` does not live long enough
 --> src/lib.rs:6:26
  |
6 |     let s: Vec<String> = arg.iter().map(|s| String::from(s)).collect();
  |                          ^^^ borrowed value does not live long enough
7 |     do_something_else(arg);
8 | }
  | - borrowed value only lives until here
  |
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 1:9...
 --> src/lib.rs:1:9
  |
1 | fn func<'a, T>(arg: Vec<Box<T>>)
  |         ^^

【问题讨论】:

  • 所以你想在将成员收集到s后使用arg?否则我会说使用into_iter 就完成了。

标签: rust lifetime


【解决方案1】:

约束String: From&lt;&amp;'a T&gt;,强调函数的生命周期参数'a,将允许您将对T 的引用转换为String。但是,对从迭代器获得的元素的引用'a 更具限制性(因此,它们的寿命不够长)。

由于转换应该适用于任何生命周期的引用,因此您可以将约束替换为更高等级的 trait bound (HRTB):

fn func<T>(arg: Vec<Box<T>>)
where
    for<'a> String: From<&'a T>,
{
    let s: Vec<String> = arg.iter().map(|s| String::from(s)).collect();
    do_something_else(arg);
}

在这里使用From 来获取拥有的字符串也不是我在野外见过的。也许你会对Display trait 感兴趣,这样你就可以调用to_string()

fn func<T>(arg: Vec<Box<T>>)
where
    T: Display,
{
    let _: Vec<_> = arg.iter().map(|s| s.to_string()).collect();
    // ...
}

另见:

【讨论】:

    猜你喜欢
    • 2020-01-07
    • 2018-01-01
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    相关资源
    最近更新 更多