尝试在方法中使用相同的生命周期参数时,为什么会出现 Lifetime 'a already in scope 错误?

问题描述 投票:0回答:1

在下面的代码中,我得到新方法的错误

Lifetime 'a already in scope
。使用与 A 相同的范围有什么问题?我认为这是有道理的。

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]}
    }
}
rust lifetime
1个回答
-1
投票

错误信息:

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`.

把问题说的很清楚了

删除错误的生命周期声明后:

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]}
    }
}

重新编译,你会得到:

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`.

这清楚地表明您只需要为参数添加显式生命周期:

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]}
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.