Now that async await is coming near to completion, I have been looking more at rust with web frameworks.
Here is a simple blog app I'm trying to create using tide but seems like I'm fighting with the 'static
lifetime.
- While I do understand that static lifetime lasts as long as the program and most webapps would be the same, why would tide use static lifetime of app_state? Isn't there other annotations that would work here?
- For
BlogOptions
wouldstr
orString
be preferred? When would I choose one over the other. I'm not liking the fact that I need to annotate str with'a
. It seems to make the code more verbose. - Based on the current code, how do I make
BlogOptions
andBlogOptions.path
have static lifetime in main func.
main.rs
#![feature(async_await)]
mod blog;
use blog::{Blog, BlogOptions};
use std::env;
use std::io;
fn main() -> Result<(), io::Error> {
let port = env::var("PORT")
.ok()
.and_then(|p| p.parse().ok())
.unwrap_or(8080);
let path = env::var("PATH")
.ok()
.unwrap_or("./".into());
let blog = Blog::new(&BlogOptions { path: path.as_str() });
blog.run(format!("0.0.0.0:{}", port))?;
Ok(())
}
blog.rs
use std::io;
use std::net::ToSocketAddrs;
pub struct Blog<'a> {
options: &'a BlogOptions<'a>,
}
pub struct BlogOptions<'a> {
pub path: &'a str,
}
impl Blog<'static> {
pub fn new(options: &'static BlogOptions) -> Self {
Blog { options }
}
pub fn run(self, address: impl ToSocketAddrs) -> Result<(), io::Error> {
let mut app = tide::App::with_state(self);
app.at("/").get(|_| async move { "Hello world!" });
app.run(address)?;
Ok(())
}
}
error
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:20:27
|
20 | let blog = Blog::new(&BlogOptions { path: path.as_str() });
| -----------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-- temporary value is freed at the end of this statement
| | |
| | creates a temporary which is freed while still in use
| argument requires that borrow lasts for `'static`
error[E0597]: `path` does not live long enough
--> src/main.rs:20:47
|
20 | let blog = Blog::new(&BlogOptions { path: path.as_str() });
| ^^^^---------
| |
| borrowed value does not live long enough
| argument requires that `path` is borrowed for `'static`
...
23 | }
| - `path` dropped here while still borrowed
I'm still learning rust so feel free to provide better solutions on how I could had written blog.rs
besides just static lifetimes.