Parameter type may not live long enough (with threads)
这类似于Parameter type是否可能寿命不长?,但是我对解决方案的解释似乎无效。 我最初的简化测试用例是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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); }); } } |
这给了我错误:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 || { | ^^^^^^^^^^^^^ |
我没有制作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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); }) } } |
现在这给了我错误:
1 2 3 4 5 6 7 | 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` |
我认为
可以使用适当的API解除
但是,
此外,