Skip to content

Instantly share code, notes, and snippets.

@JSila
Last active July 21, 2020 07:49
Show Gist options
  • Save JSila/d58e2fdbba94309105159b008591dcc1 to your computer and use it in GitHub Desktop.
Save JSila/d58e2fdbba94309105159b008591dcc1 to your computer and use it in GitHub Desktop.
Rust: updating an array field of mutable struct in a seperate function
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