Copy or reborrow... or something else

Hi all,

I have a question about this code. I know it's bad practice and it doesn't compile due to this.

What I'm wondering is what actually happens here internally, because on the one hand the compiler output looks like there happend a reborrow of a mutable refernce as an immutable reference, but on the other hand I know that the shared field of the struct is Copy so there shouldn't be a reborrow, as it can just be copied or am I wrong? Might it be that the lifetime of the mutable reference gets just somehow extended for the lifetime of the immutable reference without an actual reborrow?


That's wrong due to the signature.

The signature

fn shared_func(&mut self) -> &[u8]


fn shared_func<'b>(&'b mut self) -> &'b [u8]

so the compiler considers the lifetime of the returned borrow to be tied to that of self. (Actually, it's neither a verbatim copy nor a reborrow – it's the coercion of &'a [u8] to &'b [u8] where 'b is shorter than 'a, but it can be viewed as "the coercion of a copy" or a "reborrow with a shorter lifetime" just as well, at least in this trivial case.)

What you wanted to write is

fn shared_func(&mut self) -> &'a [u8]



That was fast! :smiley: Thank you very much! :slight_smile: