Last active
July 21, 2020 07:49
Star
You must be signed in to star a gist
Rust: updating an array field of mutable struct in a seperate function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::env; | |
use std::fs::File; | |
use serde::{Deserialize, Serialize}; | |
#[derive(Serialize, Deserialize, Debug)] | |
struct Site { | |
id: String, | |
#[serde(skip_serializing_if = "Option::is_none")] | |
status_changed: Option<bool>, | |
#[serde(skip_serializing_if = "Option::is_none")] | |
text: Option<String>, | |
#[serde(skip_serializing_if = "Option::is_none")] | |
value: Option<f32> | |
} | |
#[derive(Serialize, Deserialize, Debug)] | |
struct Plan { | |
sites: Vec<Site> | |
} | |
fn main() { | |
let mut args = env::args(); | |
args.next(); | |
let path = args.next() | |
.expect("no argument"); | |
let file = File::open(&path) | |
.expect("can't read file"); | |
let mut plan: Plan = serde_json::from_reader(&file) | |
.expect("can't read to json"); | |
// plan.sites = plan.sites.into_iter() | |
// .map(|mut s| { | |
// s.status_changed = Option::from(true); | |
// s | |
// }) | |
// .collect(); | |
// | |
// plan.sites.iter().for_each(|s| { | |
// println!("{}, {:?}", s.id, s.status_changed) | |
// }); | |
run(&mut plan); | |
let file = File::create(&path) | |
.expect("can't create file"); | |
serde_json::to_writer_pretty(&file, &plan) | |
.expect("can't write to json file"); | |
} | |
fn run (plan: &mut Plan) { | |
for site in plan.sites.iter_mut() { | |
let id = &site.id; | |
println!("{}", id); | |
site.status_changed = Option::from(true) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment