Why do I get Lifetime 'a already in scope error when trying to use the same lifetime argument in method?

Advertisements

In the following code i get the error Lifetime 'a already in scope for the new method. What is the issue in using the same scope as A? I thought it made sense.

struct A <'a>{
    a: Vec<&'a str>,
    b: Vec<&'a str>
}

impl <'a> A<'a> {
    fn new<'a>(a: &str, b: &str, c: &str, d: &str) -> A<'a> {
        A {a: vec![a, b], b: vec![c, d]}
    }
}

>Solution :

The error message:

error[E0496]: lifetime name `'a` shadows a lifetime name that is already in scope
 --> src/lib.rs:7:12
  |
6 | impl <'a> A<'a> {
  |       -- first declared here
7 |     fn new<'a>(a: &str, b: &str, c: &str, d: &str) -> A<'a> {
  |            ^^ lifetime `'a` already in scope

For more information about this error, try `rustc --explain E0496`.

makes the problem very clear.

Once you delete the errornoues lifetime declaration:

struct A <'a>{
    a: Vec<&'a str>,
    b: Vec<&'a str>
}

impl <'a> A<'a> {
    fn new(a: &str, b: &str, c: &str, d: &str) -> A<'a> {
        A {a: vec![a, b], b: vec![c, d]}
    }
}

and recompile, you will get:

error[E0621]: explicit lifetime required in the type of `a`
 --> src/lib.rs:8:9
  |
7 |     fn new(a: &str, b: &str, c: &str, d: &str) -> A<'a> {
  |               ---- help: add explicit lifetime `'a` to the type of `a`: `&'a str`
8 |         A {a: vec![a, b], b: vec![c, d]}
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime `'a` required

error[E0621]: explicit lifetime required in the type of `b`
 --> src/lib.rs:8:9
  |
7 |     fn new(a: &str, b: &str, c: &str, d: &str) -> A<'a> {
  |                        ---- help: add explicit lifetime `'a` to the type of `b`: `&'a str`
8 |         A {a: vec![a, b], b: vec![c, d]}
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime `'a` required

error[E0621]: explicit lifetime required in the type of `c`
 --> src/lib.rs:8:9
  |
7 |     fn new(a: &str, b: &str, c: &str, d: &str) -> A<'a> {
  |                                 ---- help: add explicit lifetime `'a` to the type of `c`: `&'a str`
8 |         A {a: vec![a, b], b: vec![c, d]}
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime `'a` required

error[E0621]: explicit lifetime required in the type of `d`
 --> src/lib.rs:8:9
  |
7 |     fn new(a: &str, b: &str, c: &str, d: &str) -> A<'a> {
  |                                          ---- help: add explicit lifetime `'a` to the type of `d`: `&'a str`
8 |         A {a: vec![a, b], b: vec![c, d]}
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime `'a` required

For more information about this error, try `rustc --explain E0621`.

Which makes it clear that you need to just add the explicit lifetime for the parameters:

struct A <'a>{
    a: Vec<&'a str>,
    b: Vec<&'a str>
}

impl <'a> A<'a> {
    fn new(a: &'a str, b: &'a str, c: &'a str, d: &'a str) -> A<'a> {
        A {a: vec![a, b], b: vec![c, d]}
    }
}

Leave a ReplyCancel reply