Trait and lifetimes


#1

Given this simple code:

trait AsBytes {
    fn as_bytes(&self) -> &[u8];
}

fn splitI<'a, I: 'a + AsBytes>(foo: I) -> (I, &'a [u8]) {
    let bytes = foo.as_bytes();
    (foo, bytes)
}

Rust (1.17) complains that "foo does not live long enough". I thought that, by using I: 'a, I told rust that anything implementing I lives at least as long as 'a, but there is clearly something I’m missing.


#2

I’m not sure about the lifetime annotations, but what you’re trying to do may not be allowed anyway.

In Rust it’s not possible to have a data structure that both owns the data and has a reference to the owned data, such as (foo, &foo.bar).

You can have multiple references though:

fn splitI<'a, I: 'a + AsBytes>(foo: &'a I) -> (&'a I, &'a [u8]) {
    let bytes: &'a _ = foo.as_bytes();
    (foo, bytes)
}

#3

It’s not allowed, yeah. ‘foo’ is moved in and out of that fn and the reference, if allowed, would point to invalid memory once it’s moved out of the fn.


#4

I see. Thanks for the pointer.