In a Rust application, I have a struct that does roughly the following:
struct Client {
token: Option<String>,
}
impl Client {
pub async fn login(&mut self) {
// ...
self.token = Some(token);
}
}
In a different struct, which is intended to represent the lifetime of an application "session" (e.g. users cannot interact without an instance of this struct in memory), I use this Client:
struct App {
client: Client,
}
impl App {
pub fn new() -> Self {
Self {
client: Client { token: None }
}
}
}
So far so good.
I recently introduced a separate struct that I would like to share the client with, who also should be owned by App
. Something like the following (which omits lifetimes and uses Option to avoid a local reference):
struct Store {
client: Option<&Client>,
}
struct App {
client: Client,
store: Store,
}
impl App {
pub fn new() -> Self {
let client = Client { token: None }
Self {
client,
store: Store { client: &client }
};
}
}
I believe this last block has issues with local references, but setting that aside, is this pattern possible? Or do all shared references need to be immutable?
Is there a Rust-friendly way to share a client that may become authenticated by an unrelated call like this?