我有以下 struct :
use std::sync::Mutex;
pub struct Message {
id: String,
content: String,
last_read: Option<String>,
uuid: String,
}
impl Message {
pub fn get_uuid(&self) -> String {
self.uuid.to_owned()
}
}
pub struct Queue {
queue: Vec<Message>, // the actual queue
read_timeout: u32, // the amount of time a message is hidden from consumers
size: u32, // should always be the same as queue.len()
uuid: String,
}
pub struct AppState {
pub queues: Mutex<Vec<Queue>>,
}
最后,我有一些处理数据的函数.他们有重复的逻辑,正如你在下面看到的.他们在得到queue
英镑后做的事情不同,但检索队列的方式是相同的.
pub async fn add_message(
data: AppState
) {
let queue_uuid = &String::from("my uuid");
let queue_mutex = data.queues.lock();
let mut queues = match queue_mutex {
Ok(q) => q,
Err(_) => return,
};
// find matching queue
let queue = queues.iter_mut().find(|q| q.uuid == *queue_uuid);
}
pub async fn get_message(
data: AppState
) {
let queue_uuid = &String::from("my uuid");
let queue_mutex = data.queues.lock();
let mut queues = match queue_mutex {
Ok(q) => q,
Err(_) => return,
};
// find matching queue
let queue = queues.iter_mut().find(|q| q.uuid == *queue_uuid);
// once the queue is found, do some stuff with it
}
我想要推翻这一逻辑.
impl AppState {
pub fn get_queues(&self) -> &Mutex<Vec<Queue>> {
&self.queues
}
pub fn get_queue_by_id(&mut self, uuid: String) -> Result<&mut Queue, String> {
let queue_mutex = self.queues.lock();
let mut queues = match queue_mutex {
Ok(q) => q,
Err(_) => return Err(String::from("Whoops! Something went wrong")),
};
match queues.iter_mut().find(|q| q.uuid == uuid) {
None => Err(format!("Could not find queue with uuid {}", uuid)),
Some(q) => Ok(q),
}
}
}
然而,这将产生一个错误,因为我不能返回q
,因为它将在函数返回时被删除.对此有什么好的解决方案吗?
附注:我知道这样做可能会更有效率--例如,使用散列映射而不是向量来存储当前队列.我是一个铁 rust 新手,打算对此进行大量重构,所以任何反馈都是有帮助的!谢谢!