《BEGINNING RUST PROGRAMMING》---读书随记(8)

BEGINNING RUST PROGRAMMING

Author: Ric Messier

如果需要电子书的小伙伴,可以留下邮箱,看到了会发送的

Chapter 9 No(SQL) Going

ASSERTIONS

Design by Contract

use contracts::*;

struct BigValue {
    localval: i32
}

impl BigValue {
    #[pre(x > 0, "x was not sufficiently large")]
    #[post(x < 15, "x is too large")]
    fn doSomething(mut self, x: i32)
    {
        println!("{}", x);
        self.localval = x;
    }
}

fn main() {
    let y = BigValue{
        localval: 2
    };
    y.doSomething(-1);
}

验证函数的入参和返回值,不符合的都会直接panic

WORKING WITH MONGODB

use mongodb::{sync::Client};
use mongodb::bson::doc;
use serde_json;
use serde::{Serialize, Deserialize};
use std::fs::File;
use std::io::BufReader;

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: i32,
    occupation: String,
    location: String,
    phone: String
}

fn read_records(filename: &str) {
    let file = File::open(filename).unwrap();
    let buf_reader = BufReader::new(file);
    let deserializer = serde_json::Deserializer::from_reader(buf_reader);
    let iterator = deserializer.into_iter::<serde_json::Value>();
    for item in iterator {
        let p: Person = serde_json::from_str(&item.unwrap().to_string()).unwrap();
        println!("Populating data");
        match db_populate(p) {
            Ok(_o) => (),
            Err(e) => println!("Unable to insert data because of {}", e)
        };
    }
}

fn db_populate(record: Person) -> mongodb::error::Result<()> {
    let client = Client::with_uri_str("mongodb://localhost:27017")?;
    let collection = client.database("customer_info").collection("people");
    let data = bson::to_bson(&record).unwrap();
    let document = data.as_document().unwrap();
    let insert_result = collection.insert_one(document.to_owned(), None)?;
    let data_insert_id = insert_result
        .inserted_id
        .as_object_id()
        .expect("Retrieved _id should have been of type ObjectId");
    println!("Inserted ID is {}", data_insert_id);
    Ok(())
}

fn main() {
    const FILENAME: &str = "people.json";
    read_records(FILENAME);
}
[dependencies]
"bson" = "*"
"serde_json" = "*"
"serde" = "*"

[dependencies.mongodb]
version = "1.1.0"
default-features = false
features = ["sync"]

感兴趣的可以详细看书

posted @   huang1993  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示