相关疑难解决方法(0)

如何将 MongoDB 中的文档反序列化为 Rust 结构?

这是我迄今为止的尝试。我不明白如何告诉 Rust 将 MongoDB 结果反序列化为结构。

我已经定义了一个名为的结构Thing,我希望将数据映射到该结构。

#[macro_use(bson, doc)]
extern crate bson;
extern crate mongodb;
#[macro_use]
extern crate serde_derive;

use mongodb::db::ThreadedDatabase;
use mongodb::{Client, ThreadedClient};

fn main() {
    let client =
        Client::connect("localhost", 27017).expect("Failed to initialize standalone client.");

    let coll = client.db("bestestDB").collection("things");

    let doc = doc! {
        "$text": { "$search": "Love" },
    };

    #[derive(Serialize, Deserialize, Debug)]
    pub struct Thing {
        #[serde(rename = "_id")] // Use MongoDB's special primary key field name when serializing
        pub id: String,
        pub name: String,
        pub image: …
Run Code Online (Sandbox Code Playgroud)

mongodb rust serde

5
推荐指数
0
解决办法
1105
查看次数

当没有类型参数或归属时,如何暗示值的类型?

我正在尝试将我的 struct 转换为 a HashMap,但是在 impl 块中时我无法这样做。由于 crate约束,我只能&self用作resolve函数的参数。

use std::collections::HashMap;

pub enum Value {
    Int(i64),
    Object(HashMap<String, Value>),
}

pub struct WeatherSettings {
    forecast_days: i64,
}

impl WeatherSettings {
    fn resolve(&self) -> Value {
        let json_object: HashMap<String, Value> = *self.into();
        Value::Object(json_object)
    }
}

impl From<WeatherSettings> for HashMap<String, Value> {
    fn from(weather: WeatherSettings) -> HashMap<String, Value> {
        let mut json_object = HashMap::new();
        json_object.insert("forecast_days".to_owned(),
                           Value::Int(weather.forecast_days));
        return json_object;
    }
}

fn main() {}
Run Code Online (Sandbox Code Playgroud)

更直接,我得到错误:

use std::collections::HashMap;

pub …
Run Code Online (Sandbox Code Playgroud)

rust

2
推荐指数
1
解决办法
946
查看次数

标签 统计

rust ×2

mongodb ×1

serde ×1