【问题标题】:Lifetime with shared state具有共享状态的生命周期
【发布时间】:2019-03-20 10:52:47
【问题描述】:

我想拥有:

  • 具有AppServicesAppState
  • 这个AppServices应该有服务IdService
  • IdService 本身应该可以访问 AppState

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

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

【问题讨论】:

    标签: rust lifetime


    【解决方案1】:

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

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

    Playground

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

    但是,除了生命周期问题之外,您还有一个循环数据结构。如果你想在结构之间共享数据,有一些特定的智能指针,如Rc 和多线程应用程序Arc

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多