I'm fairly new to rust and have been trying to learn by actually creating simple websites.
I was able to embed a trait inside of a struct. Rust Playground
use std::env;
pub trait BlogBackend {}
pub struct AppState {
pub host: String,
pub port: String,
pub blog: Box<dyn BlogBackend + Send + Sync>,
}
pub struct BlogFsBackend{}
impl BlogBackend for BlogFsBackend{}
impl AppState {
pub fn new() -> AppState {
AppState {
host: env::var("HOST").unwrap_or("127.0.0.1".to_string()),
port: env::var("PORT").unwrap_or("8080".to_string()),
blog: Box::new(BlogFsBackend{}),
}
}
pub fn addr(&self) -> String {
format!("{}:{}", self.host, self.port)
}
}
Here is how I'm using app state with tide.
pub mod appstate;
use appstate::AppState;
pub async fn start() -> Result<(), std::io::Error> {
let state = AppState::new();
let addr = state.addr();
let mut app = tide::with_state(state);
app.at("/").get(|_| async move { "Hello world!" });
app.listen(addr).await?;
Ok(())
}
Here is tide's with_state contract.
pub fn with_state<State>(state: State) -> server::Server<State>
where
State: Send + Sync + 'static,
{
.....
}
- Is
Box<dyn trait>the way to embed trait inside of a struct? Are there other alternatives? - I never implemented
Send + SyncforBlogFsBackendbut somehow rust seems to auto implement it since as soon as I removeSend + SyncfromBox<dyn BlogBackend + Send + Sync>it fails with compilation error sincewith_staterequires it. Can someone explain how this works. - Is it preferred to use
Stringforhostin struct or&str?
