I came across a problem which I thought would be perfect to use trait objects for. While I managed to make it work, it looks far more complicated than it should so I would like to know if there is a more optimal way to use trait objects.
Exemplified code:
/* This takes a slice of objects implementing trait and compares each of
them with all other objects in the slice, if they interact with each other
both objects should call a certain function with the other object as a parameter.
This is used for a collision system, in case you know of a better way to solve this please
let me know. */
fn foo(objects: &mut [Box<Trait>]) {
let mut active_objects: Vec<&mut Box<Trait>> = vec!();
for current in objects.iter_mut() {
for other in active_objects.iter_mut() {
if (**current).is_interacting(&***other) {
current.boo(&mut ***other);
other.boo(&mut **current);
}
}
active_objects.push(current);
}
}
trait Trait {
fn boo(&mut self, other: &mut Trait);
fn is_interacting(&self, other: & Trait) -> bool;
}
Is there a way I don't have to write something like &***
every time I want to use the actual object?
if (**current).is_interacting(&***other)
becomes if current.is_interacting(&***other)
as Rust automatically dereferences in this case.