Consider:
- a struct with a borrowed reference field;
- a function taking a reference to this struct and returning a reference borrowed from the inner field.
This does actually compile:
struct B<'a> {
buf: &'a [u8],
}
fn foo<'a>(b: &B<'a>) -> &'a [u8] {
&b.buf[..]
}
However if the reference within the struct is mutable, so the function can first update b.buf
:
struct B<'a> {
buf: &'a mut [u8],
}
… then the compiler says:
src/lib.rs:6:6: 6:15 error: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements [E0495]
src/lib.rs:6 &b.buf[..]
^~~~~~~~~
I can't quite put my head around the reason why is this? Why mutability changes anything about b.buf
having the lifetime 'a
and foo<'a>
returning a reference with the same lifetime?
P.S. This is a distilled example. The real world task is to have a parser with a caller-supplied buffer returning parsed slices from that buffer.