共享状态的生命周期

Lifetime with shared state

我想要:

以下是我提出的想法,但我无法正确完成生命周期标记。

struct IdService<'a> {
    name: String,
    state: &'a AppState,
}
struct AppServices<'a> {
    id: Option<&'a IdService>,
}

struct AppState<'a> {
    services: &'a AppServices,
}

impl<'a> AppState<'a> {
    pub fn new() -> Self {
        AppState {
            services: AppServices { id: None },
        };
    }
}

fn main() {
    let mut state = AppState::new();
    let id_service = IdService {
        name: "test".to_string(),
        state: state,
    };
    let services = AppServices {
        id: Some(id_service),
    };
    state.services = services;
}

编译器输出:

error[E0106]: missing lifetime specifier
 --> src/main.rs:3:16
  |
3 |     state: &'a AppState,
  |                ^^^^^^^^ expected lifetime parameter

error[E0106]: missing lifetime specifier
 --> src/main.rs:6:20
  |
6 |     id: Option<&'a IdService>,
  |                    ^^^^^^^^^ expected lifetime parameter

error[E0106]: missing lifetime specifier
  --> src/main.rs:10:19
   |
10 |     services: &'a AppServices,
   |                   ^^^^^^^^^^^ expected lifetime parameter

由于您的第一个结构有一个引用,该引用本身引用了另一个结构,您还需要指定这些子结构的生命周期:

struct AppState<'a> {
    services: &'a AppServices<'a>,
}

Playground

这样你就是在告诉编译器 AppStateAppServices 生命周期是绑定的,因此 AppServices 成员也有生命周期 'a

但是,除了生命周期问题之外,您还有一个循环数据结构。如果你想在结构之间共享数据,有一些特定的智能指针,如 Rc and for multithreaded applications Arc

您可以共享 Arc 智能指针并在 Mutex 的帮助下改变数据,以保证线程的单一访问,而不是共享结构的原始指针。

A solution that uses an Arc 解决这样一个循环数据结构问题。