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>>) {}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨说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>>)
| ^^
Run Code Online (Sandbox Code Playgroud)
该约束String: From<&'a T>强调函数的生命周期参数'a,允许您将引用转换T为a String.但是,从迭代器获得的元素的引用比(因此,它们不能长寿)更具限制性'a.
由于转换应该适用于任何生命周期的引用,您可以用更高排名的特征限制(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);
}
Run Code Online (Sandbox Code Playgroud)
使用From这里获得一个拥有的字符串也不是我在野外看到的东西.也许你会对这个Display特性感兴趣,这样你就可以打电话to_string():
fn func<T>(arg: Vec<Box<T>>)
where
T: Display,
{
let _: Vec<_> = arg.iter().map(|s| s.to_string()).collect();
// ...
}
Run Code Online (Sandbox Code Playgroud)
也可以看看: