假设我有一个包含引用的结构体,还有另一个引用该结构体的结构体,就像这样:
struct Image<'a> {
pixel_data: &'a mut Vec<u8>,
size: (i32, i32),
}
struct SubImage<'a> {
image: &'a mut Image<'a>,
offset: (i32, i32),
size: (i32, i32),
}
这些结构体有着几乎一模一样的接口,唯一的区别在于SubImage
会根据其偏移量来调整位置参数,然后将其转发到包含的Image
引用相应函数中。我希望这些结构体可以基本上互换使用,但我似乎无法搞清楚如何正确处理生命周期。最初,我只是使用了Image
,并且可以简单地传递对象,从未对生命周期说明涉及到:
fn main() {
let mut pixel_data: Vec<u8> = Vec::new();
let mut image = Image::new(&mut pixel_data, (1280, 720));
render(&mut image);
}
fn render(image: &mut Image) {
image.rect_fill(0, 0, 10, 10);
}
然后我创建了
SubImage
,并想要进行以下操作:fn render2(image: &mut Image) {
let mut sub = SubImage {
image: image, // line 62
offset: (100, 100),
size: (600, 400),
};
sub.rect_fill(0, 0, 10, 10);
}
然而,这会导致编译器错误:
main.rs:62:16: 62:21 error: cannot infer an appropriate lifetime for automatic coercion due to conflicting requirements
编译器的建议是将签名更改为以下内容:
fn render2<'a>(image: &'a mut Image<'a>)
然而,这只是把问题推到了调用
render2
并拥有一个 &mut Image
的函数上。这很恼人,因为函数调用层数较深,当我只使用 Image
类(也有一个引用)并内联调整偏移量时,我不需要这样做。首先,我甚至不理解为什么需要这样做(尽管我对 Rust 生命周期的理解有限)。其次(我的主要问题),是否有什么我可以做到
SubImage
,使得这些显式生命周期不必要?