0

I have object MutableContent which can normally create MutableSubcontent object that borrows mutable reference to data, but Iterator implementation will fail while compilation. If I remove mut both in MutableSubcontent.buf and in MutSubcontentIter.buf it compiles normally

Example (explanations in comments):

struct MutableContent<'a> {
    buf: &'a mut [u8],
}

struct MutableSubcontent<'a> {
    /// (1) If remove `mut` there are no compiler errors
    buf: &'a mut [u8],
}

struct MutSubcontentIter<'a> {
    /// (1) If remove `mut` there are no compiler errors
    buf: &'a mut [u8],
    current: u32
}

impl<'a> MutableContent<'a> {
    fn new_subcontent(&mut self) -> MutableSubcontent {
        /// Compiles normally
        MutableSubcontent { buf: self.buf }
    }
}

impl<'a> Iterator for MutSubcontentIter<'a> {
    type Item = MutableSubcontent<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.current >= 5 {
            return None;
        }
        /// Does not compile with error:  associated function was supposed to return
        /// data with lifetime `'a` but it is returning data with lifetime `'1`
        Some(MutableSubcontent { buf: self.buf })
    }
}

Is it time to use RefCell instead or there are more concise solution?

Arsynth
  • 761
  • 9
  • 22

0 Answers0