Livetime error , new


Hi , I’m new in rust and livetimes , my question is because I have this error in this code

"fn new(reg: &'a str, reg1: &'b str) -> &'a Heli {
  |                                                ^^^^ expected 2 lifetime parameters"
I think reg and reg1 are in distints scopes and 'a , 'b are their livetimes , but why this error?? I don't anderstand.
Sorry for my bad inglish

struct Heli<'a,'b>{
    reg: &'a str,
    reg1: &'b str
impl <'a, 'b> Heli<'a, 'b>{
    fn new(reg: &'a str, reg1: &'b str) -> &'a Heli {
        Heli {
            reg: reg,
            reg1: reg1
    fn hover(&self) {
        println!("{} is hovering {}", self.reg, self.reg1);
fn main() {
    let reg = "G-HONI";
        let reg1 = "G-HONA";
        let heli = Heli::new(&reg, &reg1);`



Just a case of using right syntax for return value.

fn new(reg: &'a str, reg1: &'b str) -> Heli<'a, 'b> {


You probably meant

fn new(reg: &'a str, reg1: &'b str) -> Heli<'a, 'b>

which in this context of an impl block can be summarized as

fn new(reg: &'a str, reg1: &'b str) -> Self

The function new returns a Heli with inner references (and thus lifetime parameters), not a reference to some Heli struct of infinite lifetime.


But if function new returns a &str , is necesary only write 'a livetime?


Yes. In a nutshell, the difference between those syntax is as follows:

  • The syntax &'a str means “A reference to a string of lifetime a”. If you wanted references to other kinds of data, you could write it down similarly: &'a i32, &'a bool, etc.
  • The syntax MyStruct<'a> means “A struct containing references to data of lifetime a”.

In the latter case, there is an extra level of indirection that does not exist in the former case.


For completeness, you could also have &'c Heli<'a, 'b>; that’s a reference, of lifetime 'c, to a Heli struct that itself has references of lifetimes 'a and 'b.


Ok , thanks for responses Little by little I understand livetimes