Dzwebs.Net

撰写电脑技术杂文十余年

rust之Vec添加多个struct后变字符串再变Value(json)(Value最后遍历获取元素值)

Admin | 2023-2-10 15:26:50 | 被阅次数 | 909

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆

  如题所示,在rust中Vec添加多个struct后变字符串再变Value(json)(Value最后遍历获取元素值)。

  大家可能知道,如果想从Value(json) 获取元素的值,或许比过蜀道还难,这个rust真不是好惹的。

  代码如下:

use serde_json::json;
use serde_json::{Value};
use serde_json::{Result};
use serde::{Deserialize, Serialize};
#[derive(Serialize)]
#[derive(Debug)]
struct myinfor{
name:String,work:String
}
fn main(){
    println!("rust开始!");
let f1=myinfor{name:String::from("青山"),work:String::from("搬砖")};
let f2=myinfor{name:String::from("云南青山"),work:String::from("网络劳工")};
let f3=myinfor{name:String::from("青山大队长"),work:String::from("挑沙灰")};

let mut mystruct:Vec<myinfor>=Vec::new();
mystruct.push(f1);
mystruct.push(f2);
mystruct.push(f3);

println!("输出vec中包含多个struct看看:{:?}",mystruct);
println!("------------------------------------------------------------------------");

for i in &mystruct{
println!("每一个Vec:{:?}",i);
}
println!("------------------------------------------------------------------------");
let jsonstr = serde_json::to_string(&mystruct).unwrap();
println!("vec中包含多个struct变字符串:{:?}",jsonstr);
println!("------------------------------------------------------------------------");


let myjson:Value = serde_json::from_str(&jsonstr).unwrap();
    println!("vec中包含多个struct之字符串变Value:{:?}", myjson);
println!("------------------------------------------------------------------------");

for i in myjson.as_array().unwrap(){
if i["name"] == "青山"{
println!("终于获得 {}", i["name"]);
break;
}
}
println!("------------------------------------------------------------------------");
println!("rust结束!");
}

  程序运行结果我下图。


  知识拓展:代码解释

  大家请注意

for i in myjson.as_array().unwrap(){
if i["name"] == "青山"{
println!("终于获得 {}", i["name"]);
break;
}
}
  myjson是Value类型的,想获取其值,不难,但是想使用遍历的方法获取其值,就难了。所以,这里,不得不使用myjson.as_array().unwrap()方能解决问题。


该杂文来自: 最新技术

上一篇:rust enum枚举结构通过impl关键字获取其变量值的

下一篇:rus之dbg!与Display与format!的使用

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计