Lifetime annotation in a trait

Hello,
I am new to Rust. and I am implementing something about Diameter Protocol.

I got a lifetime mismatch error.

I defined a trait as below:

trait Avp where Self:Sized {
type V;
fn get_data(&self) -> Self::V;
fn get_header(&self) -> &AvpHeader;
fn new<'a>(header:AvpHeader,data:&'a [u8]) -> Option;
}

I define a struct AvpOctetString with a borrowed value of a slice of u8:

pub struct AvpOctetString<'a> {
header: AvpHeader,
payload: &'a [u8],
}

When I try implementing this trait for this struct, I can't compile:

impl<'a> Avp for AvpOctetString<'a> {
type V = &'a [u8];

fn get_data(&self) -> &'a [u8]    {
    self.payload
}

fn get_header(&self) -> &AvpHeader  {
    &self.header
}

fn new(header:AvpHeader, data:&'a [u8]) -> Option<AvpOctetString>   {
    let length = header.get_length();
    Some(AvpOctetString{
        header,
        payload:data[0..length],
    })
}

}

I got compile error like this:
error[E0308]: method not compatible with trait
--> src/message/avp.rs:27:5
|
27 | / fn new(header:AvpHeader, data:&'a [u8]) -> Option {
28 | | let length = header.get_length();
29 | | Some(AvpOctetString{
30 | | header,
31 | | payload:data[0..length],
32 | | })
33 | | }
| |_____^ lifetime mismatch
|
= note: expected type fn(message::avp_header::AvpHeader, &'a [u8]) -> std::option::Option<message::avp::AvpOctetString<'a>>
found type fn(message::avp_header::AvpHeader, &'a [u8]) -> std::option::Option<message::avp::AvpOctetString<'a>>

My intention is to avoid data copying, so that AvpOctetString.

Could you please help me?

Thanks,
Best regards,

Please put code and error messages in code blocks:

```
Some code
```

In new you should do payload:&data[0…length], (notice the ampersand). Also the function should return Option<AvpOctetString<'a>> (notice the 'a)

I added the code to the playground and got it to compile: Rust Playground

I think the main problem was that there are two lifetimes - one on the AvpOctetString struct that is parts of its definition, and another lifetime on the new() function which states that the return value has the same lifetime as the data parameter.

Thanks a lot.

I was fooled that, I used the same name "'a" in both new() function and in struct definition.

I thought those are the same lifetime annotation..

Hello,
By the way, I have another question:

about following code:

pub struct AvpOctetString<'s> {
    header: AvpHeader,
    payload: &'s [u8],
}

I understand that, the lifetime annotation here 's does not have any effect until do implement the methods in impl block, am I correct?

In other words, the lifetime annotation here " 's " does not mean that, the lifetime of AvpOctetString struct have the same lifetime as the reference to payload.

Please correct me if I am wrong.