How can I pass a variable initialized in main to a

2019-08-27 02:40发布

I have a variable that gets initialized in main (line 9) and I want to access a reference to this variable inside of one of my route handlers.

#[get("/")]
fn index() -> String {
    return fetch_data::fetch(format!("posts"), &redis_conn).unwrap(); // How can I get redis_conn?
}

fn main() {
    let redis_conn = fetch_data::get_redis_connection(); // initialized here

    rocket::ignite().mount("/", routes![index]).launch();
}

In other languages, this problem would be solvable by using global variables.

1条回答
淡お忘
2楼-- · 2019-08-27 03:27

Please read the Rocket documentation, specifically the section on state.

Use State and Rocket::manage to have shared state:

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket; // 0.4.2

use rocket::State;

struct RedisThing(i32);

#[get("/")]
fn index(redis: State<RedisThing>) -> String {
    redis.0.to_string()
}

fn main() {
    let redis = RedisThing(42);

    rocket::ignite()
        .manage(redis)
        .mount("/", routes![index])
        .launch();
}

If you want to mutate the value inside the State, you will need to wrap it in a Mutex or other type of thread-safe interior mutability.

See also:

this problem would be solvable by using global variables.

See also:

查看更多
登录 后发表回答