[英]Mix lifetimes of references in Vec
I am attempting to generate a Vec<&'b Color>
from Vec<&'a Color>
: 我正在尝试从Vec<&'a Color>
生成Vec<&'b Color>
Vec<&'a Color>
:
impl <'a> Canvas<'a> {
pub fn modify<'b>(&self, update: Update) -> Canvas<'b> {
let x = update.x;
let y = update.y;
let colors: Vec<&'b Color> = self.colors.iter().enumerate().map(move |(index, color)| {
if index == self.width * y + x { update.color } else { color }
})
.collect();
Canvas { width: self.width, height: self.height, colors: colors }
}
}
However, I get the following error: 但是,出现以下错误:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/canvas.rs:51:50
|
51 | let colors: Vec<&'b Color> = self.colors.iter().enumerate().map(move |(index, color)| {
| ^^^^
How can I create a Vec
of colors, all but one with lifetime 'a
, and the remaining with lifetime 'b
? 如何创建Vec
颜色,除了一个颜色,所有颜色的寿命为'a
,其余颜色为寿命'b
?
If needed, the relevant definitions are as follows: 如果需要,相关定义如下:
#[derive(Debug, PartialEq, Eq)]
pub enum Color {
White,
Red,
Blue,
Green,
Purple,
Orange
}
pub struct Update<'a> {
color: &'a Color,
x: usize,
y: usize
}
pub struct Canvas<'a> {
width: usize,
height: usize,
colors: Vec<&'a Color>
}
How can I create a
Vec
of colors, all but one with lifetime'a
, and the remaining with lifetime'b
? 如何创建Vec
颜色,除了一个颜色,所有颜色的寿命为'a
,其余颜色为寿命'b
?
You cannot . 你不能 。 Lifetimes are generics, and just like it doesn't make sense to have "a Vec<T>
, all but one of T
is the type String
, and the remaining T
is the type bool
", it doesn't make sense to do so with lifetimes. 寿命是仿制药,只是喜欢它没有意义有“一个Vec<T>
但所有的一个T
的类型为String
,其余T
的类型是bool
”,它没有意义做一辈子
What you can do is unify the lifetimes: 您可以做的是统一生命周期:
impl<'a> Canvas<'a> {
pub fn modify(&self, update: Update<'a>) -> Canvas<'a> {
let x = update.x;
let y = update.y;
let colors = self.colors
.iter()
.enumerate()
.map(move |(index, color)| if index == self.width * y + x {
update.color
} else {
color
})
.collect();
Canvas {
width: self.width,
height: self.height,
colors: colors,
}
}
}
Here, we've said that the update.color
lifetime and the lifetime of the contained references have an intersection, and that's what the lifetime of the result will be. 在这里,我们已经说过了update.color
生命周期和所包含引用的生命周期有一个交集,这就是结果的生命周期。
Another common solution for a heterogenous collection of a fixed set of types is to introduce an enum with variants for each one: 一组固定类型的异构集合的另一个常见解决方案是为每个枚举引入一个带有变体的枚举:
pub enum Thing<'a, 'b> {
A(&'a Color),
B(&'b Color),
}
impl<'a> Canvas<'a> {
pub fn modify<'b>(&self, update: Update<'b>) -> Vec<Thing<'a, 'b>> {
let x = update.x;
let y = update.y;
self.colors
.iter()
.enumerate()
.map(move |(index, color)| if index == self.width * y + x {
Thing::B(update.color)
} else {
Thing::A(color)
})
.collect()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.