我有一个在 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();
}
在其他语言中,这个问题可以通过使用全局变量来解决。
最佳答案
请阅读 Rocket documentation ,特别是 section on state 。
使用 State
和 Rocket::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
或其他类型的线程安全内部可变性中。
另见:
- Compiler says that data cannot be shared between threads safely even though the data is wrapped within a Mutex
- Need holistic explanation about Rust's cell and reference counted types
- Share i32 mutably between threads
this problem would be solvable by using global variables.
另见:
关于rust - 如何将在 main 中初始化的变量传递给 Rocket 路由处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55384204/