Borrowed value does not live long enough when iterating over a generic value with a lifetime on the function body

本小妞迷上赌 提交于 2019-12-01 23:22:07

问题


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>>) {}

The compiler complains that arg does not live long enough. Why though?

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>>)
  |         ^^

回答1:


The constraint String: From<&'a T>, with emphasis on the function's lifetime parameter 'a, would allow you to convert a reference to T to a String. However, the reference to the elements obtained from the iterator is more restrictive than 'a (hence, they do not live long enough).

Since the conversion is supposed to work fine for references of any lifetime, you may replace the constraint with a higher ranked 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);
}

The use of From here to obtain an owned string is also not something I've seen in the wild. Perhaps you would be interested in the Display trait, so that you can call to_string():

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

See also:

  • How do I write the lifetimes for references in a type constraint when one of them is a local reference?
  • How does for<> syntax differ from a regular lifetime bound?


来源:https://stackoverflow.com/questions/53485574/borrowed-value-does-not-live-long-enough-when-iterating-over-a-generic-value-wit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!