我该如何将在主函数中初始化的变量传递给Rocket路由处理程序?

17

我有一个在main中初始化的变量(第9行),我想在我的路由处理程序中访问对此变量的引用。

#[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();
}

在其他语言中,这个问题可以通过使用全局变量来解决。

1个回答

17
请阅读Rocket文档,特别是state部分
使用StateRocket::manage来实现共享状态:
#![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();
}

如果你想要改变State中的值,你需要将其包装在一个Mutex或其他类型的线程安全内部可变性中。

另请参阅:

使用全局变量可以解决这个问题。

另请参阅:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接