I'm using the Iron framework to create a simple endpoint. I have stateful, mutable data that the endpoint needs access to.
Here's some code that shows my intention:
extern crate iron;
extern crate mount;
use iron::{Iron, Request, Response, IronResult};
use iron::status;
use mount::Mount;
static mut s_counter: Option<Counter> = None;
struct Counter {
pub count: u8
}
impl Counter {
pub fn new() -> Counter {
Counter {
count: 0
}
}
pub fn inc(&mut self) {
self.count += 1;
}
}
fn main() {
unsafe { s_counter = Some(Counter::new()); }
let mut mount = Mount::new();
mount.mount("/api/inc", inc);
println!("Server running on http://localhost:3000");
Iron::new(mount).http("127.0.0.1:3000").unwrap();
}
fn inc(req: &mut Request) -> IronResult<Response> {
let mut counter: Counter;
unsafe {
counter = match s_counter {
Some(counter) => counter,
None => { panic!("counter not initialized"); }
};
}
counter.inc();
let resp = format!("{}", counter.count);
Ok(Response::with((status::Ok, resp)))
}
This code doesn't compile:
error: cannot move out of static item
I'm hoping that there is nicer way to do this, not involving any unsafe code or static mut. My question is, what is the idiomatic way to accomplish this?