I want to create a simple struct (let's say, AppState) which owns a connection and shares it between its own fields. I tried to express it with Pin
, but it didn't work well.
#![feature(pin, arbitrary_self_types)]
use std::pin::Pin;
pub struct Connection;
pub struct UserRepository<'a>(&'a Connection);
pub struct BlogRepository<'a>(&'a Connection);
pub struct AppState<'a> {
connection: Connection,
user_repo: UserRepository<'a>,
blog_repo: BlogRepository<'a>
}
impl<'a> AppState<'a> {
pub fn new(connection: Connection) -> Self {
Self {
connection,
user_repo: UserRepository(&connection),
blog_repo: BlogRepository(&connection),
}
}
}
There are two problems:
- I cannot reference
connection
, because I move it toSelf
in constructor, but OTOH I cannot reference partially initialized variable - I don't understand how to use Pin api to allow it. Basically,
AppState
should be immovable after creation so we can use self references. But I don't get how to express it.
Please, any advice?
P.S. Don't suggest reference counting