首页 > 其他分享 >《BEGINNING RUST PROGRAMMING》---读书随记(8)

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

时间:2022-11-26 11:33:23浏览次数:41  
标签:insert use PROGRAMMING serde --- json let data 随记

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"]

感兴趣的可以详细看书

标签:insert,use,PROGRAMMING,serde,---,json,let,data,随记
From: https://www.cnblogs.com/huangwenhao1024/p/16927131.html

相关文章

  • C++ --- mingw编译提示too many sections…File too big
    现象:在WindowsQt下使用MingW编译,报错toomanysections…Filetoobig当代码中使用了大量模板时,会导致编译出的OBJ文件巨大,编译器会报错,在MSVC下错误为FatalErro......
  • k8s与Docker-九五小庞
    随着k8s作为容器编排解决方案变得越来越流行,有些人开始拿Docker和k8s进行对比,不禁问道:Docker不香吗?k8s是kubernets的缩写,’8‘代表中间的八个字符。其实Docker和......
  • 02-1-数据库中查询性能的提升(1)
                                                         ......
  • MFC-美化控件
           ......
  • Vulnhub之jangow-01-1靶机解题过程(shell有问题)
    jangow-01-1.0.1识别目标主机IP地址┌──(kali㉿kali)-[~/Vulnhub/jangow]└─$sudonetdiscover-ieth1Currentlyscanning:192.168.155.0/16|ScreenView:......
  • test-Hangman
    defhangman(word):wrong=0stages=["","--------","||","|O","|/|\",......
  • 课设-Debug
    @目录2022.11.26LikePurple1、javafx包无法识别原因1:Javafx包未导入lib文件夹原因2:JDK版本过高,取消javafx包nullnullnullnullnull课设运行遇到的问题2022.11.26LikePur......
  • 882. 细分图中的可到达节点 ----- Dijkstra算法、图
    给你一个无向图(原始图),图中有n个节点,编号从0到n-1。你决定将图中的每条边细分为一条节点链,每条边之间的新节点数各不相同。图用由边组成的二维数组edges表示,其......
  • redis-集群
    集群容量不够,redis如何进行扩容?并发写操作,redis如何分摊?另外?主从模式,薪火相传方式,主机宕机,导致ip地址发生变化,应用程序中配置需要修改对应的主机地址、端口等信息。之......
  • 14基础元器件-隔离放大器
    一、初步认识1、定义隔离放大器是一种特殊的测量放大电路,其输入、输出和电源电路之间没有直接电路耦合,即信号在传输过程中没有公共的接地端。输入电路和放大器输出之间......