Hello,
I have an object that uses a HashMap<String, T>
, which I store to MongoDB. Mongo’s Rust driver, of course, is happy so long as T implements Serialize. The trouble comes up when I want to manually access the “_id” field.
I can bound my implementation with T: From<ObjectId>
and T: TryInto<ObjectId>
, but the Bson type doesn’t implement TryInto<ObjectId>
.
I worked around it like this, below, but this trades one set of problems for another later on.
/// This trait is identical to `Into<ObjectId>`, but unlike Into<ObjectId>, I am allowed to
/// implement it on types from external crates
pub trait IntoObjectId {
fn into_object_id(self) -> ObjectId;
}
impl IntoObjectId for Bson {
fn into_object_id(self) -> ObjectId {
if let Bson::ObjectId(object_id) = self {
object_id
} else {
panic!()
}
}
}
It seems like a handy thing to be able to convert between the Bson umbrella enum and the inner types using Rust’s built-in conversion traits, in places where the behavior wouldn’t be ambiguous (like for ObjectId)
Thanks.