给定一个像这样的简单结构:
struct Server {
clients: HashMap<usize, Client>
}
访问的最佳方式Client
是&mut
什么?考虑以下代码:
use std::collections::HashMap;
struct Client {
pub poked: bool
}
impl Client {
pub fn poked(&self) -> bool {
self.poked
}
pub fn set_poked(&mut self) {
self.poked = true;
}
}
struct Server {
clients: HashMap<usize, Client>
}
impl Server {
pub fn poke_client(&mut self, token: usize) {
let client = self.clients.get_mut(&token).unwrap();
self.poke(client);
}
fn poke(&self, c: &mut Client) {
c.set_poked();
}
}
fn main() {
let mut s = Server { clients: HashMap::new() };
s.clients.insert(1, Client { poked: false });
s.poke_client(1);
assert!(s.clients.get(&1).unwrap().poked() == true);
}
我看到的仅有的两个选项是在客户端中使用RefCell
/ Cell
,这让事情看起来非常可怕:
pub struct Client {
nickname: RefCell<Option<String>>,
username: RefCell<Option<String>>,
realname: RefCell<Option<String>>,
hostname: RefCell<Option<String>>,
out_socket: RefCell<Box<Write>>,
}
或者包装clients
in RefCell
,这使得不可能有像这样的简单方法Server
:
pub fn client_by_token(&self, token: usize) -> Option<&Client> {
self.clients_tok.get(&token)
}
强迫我使用闭包(例如with_client_by_token(|c| ...)
)。