Passing a reference through two levels of structs

I have a struct with a reference, which is in turn a component of another struct. The borrow checker asks for an explicit lifetime which is already present. Everything seems to be annotated properly for lifetime pass-through, but I seem to be doing something wrong.

Playground link.



/// Additional data in full updates
#[derive(Debug, Clone, PartialEq, Default)]
pub struct UpdateAdditionalData<'a> {
    foo: &'a [u8]
}

#[derive(Debug, Clone, PartialEq)]
pub struct UpdateData<'a> {
    additional: UpdateAdditionalData<'a>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ObjectUpdateCompressedObjectData<'a> {
    pub data: &'a [u8],
}

pub fn decodeobjectupdatecompressed2a(b: &[u8]) -> Result<UpdateData, &str> {
    Ok(UpdateData{
        additional: Default::default() })}

pub fn decodeobjectupdatecompressed<'a>(od: &'a ObjectUpdateCompressedObjectData) -> Result<UpdateData<'a>, &'static str> {
     Ok(decodeobjectupdatecompressed2a(od.data)?)
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0621]: explicit lifetime required in the type of `od`
  --> src/lib.rs:24:48
   |
23 | pub fn decodeobjectupdatecompressed<'a>(od: &'a ObjectUpdateCompressedObjectData) -> Result<UpdateData<'a>, &'static str> {
   |                                             ------------------------------------ help: add explicit lifetime `'static` to the type of `od`: `&'a ObjectUpdateCompressedObjectData<'static>`
24 |      Ok(decodeobjectupdatecompressed2a(od.data)?)
   |                                                ^ lifetime `'static` required

error: aborting due to previous error

For more information about this error, try `rustc --explain E0621`.
error: could not compile `playground`

To learn more, run the command again with --verbose.

The lifetime on the Err part of decodeobjectupdatecompressed2a's result defaults to the same as on its b argument. You need to set that to be 'static for it to be compatible with the output of decodeobjectupdatecompressed.

pub fn decodeobjectupdatecompressed2a(b: &[u8]) -> Result<UpdateData, &'static str> {
    Ok(UpdateData{
        additional: Default::default() })}

The generic lifetime parameter is part of ObjectUpdateCompressedObjectData's type, and that lifetime doesn't have to be the same as the lifetime of any references to it. Applying the compiler hint allows the code to compile.

I didn't try to analyze in depth if using 'static here will fulfill what you're trying to do, but the static requirement is because your return has a static lifetime, so presumably this okay.

Right, inconsistent lifetime on the error case.

This came from oversimplifying a deeper problem. More later if I can't fix that.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.