Why do I get “missing lifetime specifier” or “wron

2020-02-15 06:22发布

I'm trying to define and implement a trait for a struct. All my implementations with generics and lifetime have problems. This must be a rookie mistake. What am I doing wrong?

main.rs

pub struct Point {
    x: i32,
    y: i32,
}

/// pure lifetime example
pub struct Foo1<'a> {
    pub first_attribute: u32,
    pub second_attribute: Point,
    third_attribute: &'a [Point],
}

pub trait Bar1<'a> {
    fn baaar();
}

impl<'a> Bar1 for Foo1<'a> {
    fn baaar() {}
}

///pure type example
pub struct Foo2<T> {
    pub first_attribute: u32,
    pub second_attribute: Point,
    third_attribute: [T],
}

pub trait Bar2<T> {
    fn baaar(&self);
}

impl<T> Bar2 for Foo2<T> {
    fn baaar(&self) {}
}

/// real world example
pub struct Foo3<'a, T: 'a> {
    pub first_attribute: u32,
    pub second_attribute: Point,
    third_attribute: &'a [T],
}

pub trait Bar3<'a, T: 'a> {
    fn baaar(&self);
}

impl<'a, T: 'a> Bar3 for Foo3<'a, T> {
    fn baaar(&self) {}
}

fn main() {
    let x = Point { x: 1, y: 1 };
    let c = Foo3 {
        first_attribute: 7,
        second_attribute: Point { x: 13, y: 17 },
        third_attribute: &x,
    };

    c.baaar();
}

compiler results

error[E0106]: missing lifetime specifier
  --> src/main.rs:17:10
   |
17 | impl<'a> Bar1 for Foo1<'a> {
   |          ^^^^ expected lifetime parameter

error[E0106]: missing lifetime specifier
  --> src/main.rs:47:17
   |
47 | impl<'a, T: 'a> Bar3 for Foo3<'a, T> {
   |                 ^^^^ expected lifetime parameter

error[E0243]: wrong number of type arguments: expected 1, found 0
  --> src/main.rs:32:9
   |
32 | impl<T> Bar2 for Foo2<T> {
   |         ^^^^ expected 1 type argument

error[E0243]: wrong number of type arguments: expected 1, found 0
  --> src/main.rs:47:17
   |
47 | impl<'a, T: 'a> Bar3 for Foo3<'a, T> {
   |                 ^^^^ expected 1 type argument

标签: generics rust
1条回答
时光不老,我们不散
2楼-- · 2020-02-15 06:43

The error messages seem pretty clear to me. They point at a type and state that the type needs a lifetime or a type. Add them:

impl<'a> Bar1<'a> for Foo1<'a> { /* ... */ }
impl<T> Bar2<T> for Foo2<T> { /* ... */ }
impl<'a, T: 'a> Bar3<'a, T> for Foo3<'a, T> { /* ... */ }

This is required because you've created parameterized traits:

pub trait Bar3<'a, T: 'a> {
//            ^^^^^^^^^^^
    fn baaar(&self);
}

None of the traits you have defined need any kind of generic parameters, so the "real" solution is just to remove them. I assume you've added them for some learning purpose not shown here though.

查看更多
登录 后发表回答