1

Can I use a mutable reference method like a value-passing one? For example, can I use

o.mth(&mut self, ...)

as

o.mth(self, ...)

This would allow me to return the result without worrying about the lifetime of o. It might involve a move closure, or some kind of wrapper?

For context, I'm trying to return a boxed iterator over CSV records using the rust-csv package but the iterator can't outlive the reader, which Reader::records(&'t mut self) borrows mutably. Contrast this with BufRead::lines(self), which consumes its reader and hence can be returned without lifetime problems.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
SeanTater
  • 182
  • 1
  • 5
  • 1
    Related: http://stackoverflow.com/q/36645452/155423, http://stackoverflow.com/q/30488928/155423, http://stackoverflow.com/q/38797960/155423 — for whatever reason, everyone wants to return a CSV iterator. – Shepmaster Dec 15 '16 at 20:07
  • Since the iterator elements aren't borrowed, it looks like the records iterator could be remade to take a `R: Read` by value. Since `&mut R` implements `Read where R: Read`, it covers both the cases. – bluss Dec 15 '16 at 20:16
  • @bluss Yeah, I was surprised by that. I assumed they would be string slices. Such a change would still be a breaking API change though, but not one that's terrible to adapt to. – Shepmaster Dec 15 '16 at 20:17

1 Answers1

2

No, you cannot. The reason that self, &self, and &mut self methods exist is because they behave differently, have different restrictions, and allow different things.

In this case, you'd probably ultimately end up trying to create an iterator that yields references to itself, which isn't allowed, or store a value and a reference to that value in the same struct, which is also disallowed.

Community
  • 1
  • 1
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366