Hello!
I'm working on some parallel and recursive code, but I can figure out only partially the lifetimes required.
The original code is the following:
use std::sync::{Arc, Mutex};
#[derive(Clone, Copy)]
pub struct Intersection<'a> {
pub object: &'a dyn Shape,
}
pub trait Shape {
fn intersections(&self) -> Vec<Intersection> {
// [Some code removed]
self.local_intersections()
}
fn local_intersections(&self) -> Vec<Intersection>;
}
pub struct Group {
pub children: Mutex<Vec<Arc<dyn Shape>>>,
}
impl Shape for Group {
fn local_intersections(&self) -> Vec<Intersection> {
// Can be done via flat_map.
let mut intersections = vec![];
let children = &*self.children.lock().unwrap();
for child in children {
intersections.extend(child.intersections().iter()); // (Copy)
}
intersections
}
}
Now, I originally thought this was the mutex not allowing access to references outside of the MutexGuard scope, however, adding appropriate lifetimes solved the problem:
use std::sync::{Arc, Mutex};
#[derive(Clone, Copy)]
pub struct Intersection<'a> {
pub object: &'a dyn Shape,
}
pub trait Shape {
fn intersections<'a>(&self) -> Vec<Intersection<'a>> {
// [Some code removed]
self.local_intersections()
}
fn local_intersections<'a>(&self) -> Vec<Intersection<'a>>;
}
pub struct Group {
pub children: Mutex<Vec<Arc<dyn Shape>>>,
}
impl Shape for Group {
fn local_intersections<'a>(&self) -> Vec<Intersection<'a>> {
// Can be done via flat_map.
let mut intersections = vec![];
let children = &*self.children.lock().unwrap();
for child in children {
intersections.extend(child.intersections().iter()); // (Copy)
}
intersections
}
}
However, if I add Shape
implementors that need to return self
, I can't figure out the lifetimes:
use std::sync::{Arc, Mutex};
#[derive(Clone, Copy)]
pub struct Intersection<'a> {
pub object: &'a dyn Shape,
}
pub trait Shape {
fn intersections<'a>(&self) -> Vec<Intersection<'a>> {
// [Some code removed]
self.local_intersections()
}
fn local_intersections<'a>(&self) -> Vec<Intersection<'a>>;
}
pub struct SomeShape {}
impl Shape for SomeShape {
fn local_intersections<'a>(&self) -> Vec<Intersection<'a>> {
vec![Intersection { object: self }] // PROBLEM HERE
}
}
pub struct Group {
pub children: Mutex<Vec<Arc<dyn Shape>>>,
}
impl Shape for Group {
fn local_intersections<'a>(&self) -> Vec<Intersection<'a>> {
// Can be done via flat_map.
let mut intersections = vec![];
let children = &*self.children.lock().unwrap();
for child in children {
intersections.extend(child.intersections().iter()); // (Copy)
}
intersections
}
}
I've also checked out the help for E0495, but I couldn't really connect to the overall problem.
Is there a solution to this? Or am I completely misunderstanding the problem (ie. this is expected when working with Mutex
)?