Example code:
use std::mem::swap;
use bson::{ doc, Bson, Document, Array };
use tap::Pipe;
#[derive(Debug)]
pub struct Data {
pub query: Document,
// and more fields...
}
fn main() {
let mut data = Data {
query: doc! {"a": 1, "b": 2},
};
let mut temp = doc! {};
swap(&mut temp, &mut data.query);
data.query = temp.into_iter()
.map(|(key, value)| doc! {key: value})
.map(|document| Bson::Document(document))
.collect::<Array>()
.pipe(|array| doc! {"$and": array});
println!("{data:#?}");
}
My main problem is this:
let mut temp = doc! {};
swap(&mut temp, &mut data.query);
data.query = temp.into_iter()
Creating the temp just to be able to swap feels wasteful.
Other solutions:
std::mem::replace- I wasn't able to make it work.- Changing the struct from
query: Documenttoquery: Option<Document>, just so I'll be able to usetake()andinsert()also annoying, since afterward i'll have tounwrap()everywhere.