如何将main中初始化的变量传递给Rocket路由处理程序?

问题描述 投票:0回答:1

我有一个在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();
}

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

rust rust-rocket
1个回答
1
投票

请阅读Rocket documentation,特别是section on state

使用StateRocket::manage来共享状态:

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;

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

也可以看看:

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

也可以看看:

© www.soinside.com 2019 - 2024. All rights reserved.