创建指向另一个的结构

时间:2018-01-12 00:49:13

标签: rust

如何创建指向作为参数接收的数据库的Item实例?

struct Something {}

struct Database<'a> {
    something: &'a Something,
}

struct Item<'a> {
    database: &'a mut Database<'a>,
}

impl<'a> Item<'a> {
    fn new(database: &'a mut Database) -> Self {
        let mut obj = Self { database };

        obj
    }
}

这会产生错误:

error[E0308]: mismatched types
  --> src/main.rs:16:13
   |
16 |             database
   |             ^^^^^^^^ lifetime mismatch
   |
   = note: expected type `&'a mut Database<'a>`
              found type `&'a mut Database<'_>`
note: the lifetime 'a as defined on the impl at 13:1...
  --> src/main.rs:13:1
   |
13 | / impl<'a> Item<'a> {
14 | |     fn new(database: &'a mut Database) -> Self {
15 | |         let mut obj = Self {
16 | |             database
...  |
20 | |     }
21 | | }
   | |_^
note: ...does not necessarily outlive the anonymous lifetime #1 defined on the method body at 14:5
  --> src/main.rs:14:5
   |
14 | /     fn new(database: &'a mut Database) -> Self {
15 | |         let mut obj = Self {
16 | |             database
17 | |         };
18 | |
19 | |         obj
20 | |     }
   | |_____^

我不明白错误是在返回类型(Self)还是其他东西。

1 个答案:

答案 0 :(得分:2)

您已将Database定义为需要生命周期参数。这意味着你还必须给它一个。错误消息在这里非常有用,您可以通过简单地执行以下操作来解决您的问题:

expected type `&'a mut Database<'a>`
   found type `&'a mut Database<'_>`

只需在<'a>的签名中将Database添加到new即可。

N.B。:始终从上到下阅读错误消息。通常通过解决第一个错误,所有连续的错误都会消失。

struct Something {}

struct Database<'a> {
    something: &'a Something
}


struct Item<'a> {
    database: &'a mut Database<'a>
}

impl<'a> Item<'a> {
    fn new(database: &'a mut Database<'a>) -> Self {
        let mut obj = Self {
            database
        };

        obj
    }
}

fn main() {
    let something = &Something {};
    let mut database = Database { something };
    let item = Item::new(&mut database);
}

Playground