Hello,
I was trying to create a generic collection trait and a default implementation with a vector working behind the scenes and it worked out as expected. However, when I added the Organism struct, that makes use of the my Collection trait, I get a bunch of confusing errors popping up. I neither understand the reasoning behind the error message nor do I think, that adding the Iterator trait is what I want. Any help would be much appreciated!
P.S.: I fixed the last error by adding the line I've commented out, again, because that didn't fix the other errors. No idea if that fix was correct or if fixing the other errors also fixes the last error and I don't need to use PhantomData.
#![feature(vec_remove_item)]
struct Organism<'a, TCollection>
where
TCollection: self::Collection<'a, std::ptr::NonNull<()>>,
{
mates: std::cell::RefCell<TCollection>,
// _phantom: std::marker::PhantomData<&'a ()>, // Is this the solution?
_pin: std::marker::PhantomPinned,
}
trait Collection<'a, Element>
where
Self: 'a + Default + IntoIterator<Item = Element>,
&'a Self: IntoIterator<Item = &'a Element>,
&'a mut Self: IntoIterator<Item = &'a mut Element>,
Element: 'a + PartialEq,
{
fn add(&mut self, item: Element);
fn contains(&self, item: &Element);
fn remove(&mut self, item: &Element);
}
struct DefaultCollection<Element>(Vec<Element>)
where
Element: PartialEq;
impl<'a, Element> Collection<'a, Element> for DefaultCollection<Element>
where
Element: 'a + PartialEq,
{
#[inline]
fn add(&mut self, item: Element) {
self.0.push(item);
}
#[inline]
fn contains(&self, item: &Element) {
self.0.contains(item);
}
#[inline]
fn remove(&mut self, item: &Element) {
self.0.remove_item(item);
}
}
impl<Element> Default for DefaultCollection<Element>
where
Element: PartialEq,
{
fn default() -> Self {
Self(Vec::new())
}
}
impl<Element> IntoIterator for DefaultCollection<Element>
where
Element: PartialEq, {
type Item = Element;
type IntoIter = std::vec::IntoIter<Element>;
#[inline]
fn into_iter(self) -> std::vec::IntoIter<Element> {
self.0.into_iter()
}
}
impl<'a, Element> IntoIterator for &'a DefaultCollection<Element>
where
Element: PartialEq, {
type Item = &'a Element;
type IntoIter = std::slice::Iter<'a, Element>;
#[inline]
fn into_iter(self) -> std::slice::Iter<'a, Element> {
self.0.iter()
}
}
impl<'a, Element> IntoIterator for &'a mut DefaultCollection<Element>
where
Element: PartialEq, {
type Item = &'a mut Element;
type IntoIter = std::slice::IterMut<'a, Element>;
#[inline]
fn into_iter(self) -> std::slice::IterMut<'a, Element> {
self.0.iter_mut()
}
}
fn main() {
let mut c = DefaultCollection::<usize>::default();
c.add(1337);
for e in &c {
println!("{}", e);
}
c.add(42);
for e in &mut c {
println!("{}", e);
*e = 123;
}
for e in &c {
println!("{}", e);
}
println!("Hello, world!");
}