【发布时间】:2015-08-18 22:41:40
【问题描述】:
这类似于Parameter type may not live long enough?,但我对解决方案的解释似乎不起作用。我最初的归结测试用例是:
use std::fmt::Debug;
use std::thread;
trait HasFeet: Debug + Send + Sync + Clone {}
#[derive(Debug, Clone)]
struct Person;
impl HasFeet for Person {}
#[derive(Debug, Copy, Clone)]
struct Cordwainer<A: HasFeet> {
shoes_for: A,
}
impl<A: HasFeet> Cordwainer<A> {
fn make_shoes(&self) {
let cloned = self.shoes_for.clone();
thread::spawn(move || {
println!("making shoes for = {:?}", cloned);
});
}
}
这给了我错误:
error[E0310]: the parameter type `A` may not live long enough
--> src/main.rs:19:9
|
16 | impl<A: HasFeet> Cordwainer<A> {
| -- help: consider adding an explicit lifetime bound `A: 'static`...
...
19 | thread::spawn(move || {
| ^^^^^^^^^^^^^
|
note: ...so that the type `[closure@src/main.rs:19:23: 21:10 cloned:A]` will meet its required lifetime bounds
--> src/main.rs:19:9
|
19 | thread::spawn(move || {
| ^^^^^^^^^^^^^
我没有创建A 'static,而是为HasFeet trait 添加了一个明确的生命周期:
use std::fmt::Debug;
use std::thread;
trait HasFeet<'a>: 'a + Send + Sync + Debug {}
#[derive(Debug, Copy, Clone)]
struct Person;
impl<'a> HasFeet<'a> for Person {}
struct Cordwainer<'a, A: HasFeet<'a>> {
shoes_for: A,
}
impl<'a, A: HasFeet<'a>> Cordwainer<'a, A> {
fn make_shoes(&self) {
let cloned = self.shoes_for.clone();
thread::spawn(move || {
println!("making shoes for = {:?}", cloned);
})
}
}
这现在给了我错误:
error[E0392]: parameter `'a` is never used
--> src/main.rs:11:19
|
11 | struct Cordwainer<'a, A: HasFeet<'a>> {
| ^^ unused type parameter
|
= help: consider removing `'a` or using a marker such as `std::marker::PhantomData`
我认为 'a 被用作 HasFeet 特征的生命周期参数。我在这里做错了什么?
【问题讨论】:
-
为什么你不想在生成
A时将其绑定到'static生命周期?我很确定您将必须,基于生成的线程可能比父线程寿命更长的事实。 restriction is pretty non-invasive as well. -
我想我不确定
'static在这种情况下的含义。我不想让在make_shoes中使用的A被泄露,因为它强制它在程序期间存在。 -
肯定不会泄露的。基本上,您会将变量的所有权转移给线程,并且不允许该变量对无法保证在程序生命周期内存在的项目有任何引用。
标签: rust