Hi,
I am new to rust and I am trying to convert this ruby script into rust:
file = File.open("aws_reserved", "rb")
reserved = file.read
res = JSON.parse(reserved)
reservations = {}
res["ReservedInstances"].each do |reservation|
key = reservation["InstanceType"] # + "/" + reservation["AvailabilityZone"]
reservations[key] = 0 if reservations.has_key?(key) == false
reservations[key] += reservation["InstanceCount"] if reservation["State"] == "active"
end
Essentially this section of the script opens a file and JSON parses it. Afterwards it uses a for each loop, putting "ReservedInstances" from res into reservation. Then depending on the conditions it adds values into reservations. My attempt for tackling this in rust:
let mut file = File::open("aws_reserved").expect("File can't be opened.");
let mut reserved = String::new();
file.read_to_string(&mut reserved).expect("File can't be read");
let res: serde_json::Value =
serde_json::from_str(&reserved).expect("Json was not well formatted.");
let mut reservations:Vec = Vec::new();
for reservation in res.get("ReservedInstances").iter(){
let key = reservation["InstanceType"];
if reservations.contains(&key){
reservations[key] = 0;
}
if reservation["State"] == "active"{
reservations[key].push(reservation["InstanceCount"]);
}
}
The JSON part seems to be working fine, but I'm having trouble with the loop. The issue is creating an equivalent for each loop. The iter statement works fine, but if I under stand the for each in ruby, it puts the value in reservation. I've tried reservation.push(res.get("InstanceType")), but I reach an error. I believe I'm not understanding the code properly. Because of this, reservations.contains(&key) gives me a mismatched type error as it expects a string instead of the enum 'Option'. Likewise that causes reservations[key] = 0 along with reservations[key].push... I would appreciate some insight clarifying my misunderstandings of the code.
Thanks.