当在函数主体上使用生命周期遍历泛型值时,借入的值的寿命不足 [英] Borrowed value does not live long enough when iterating over a generic value with a lifetime on the function body

查看:50
本文介绍了当在函数主体上使用生命周期遍历泛型值时,借入的值的寿命不足的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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的寿命不足.为什么呢?

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

推荐答案

约束String: From<&'a T>(着重函数的生命周期参数'a)可以使您将对T的引用转换为String .但是,对从迭代器获得的元素的引用比'a更具约束力(因此,它们的寿命不足).

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

由于该转换对于任何生命周期的引用都可以正常工作,因此您可以将约束替换为更高的特质限制(HRTB):

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

我在野外也没有看到在这里使用From来获得拥有的字符串.也许您会对Display性状感兴趣,因此可以调用to_string():

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();
    // ...
}

另请参阅:

  • 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?

这篇关于当在函数主体上使用生命周期遍历泛型值时,借入的值的寿命不足的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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