Here's a bit of code that returns a training from a library, or if it is not in the library it also tries to find it in the database and add it to the library first:
https://pastebin.com/bv2aSL4Q (didn't fit in post)
I believe I messed up the structure which makes the control flow not obvious.
I asked AI to fix it and it came up with this:
for training_id in training_iter {
let training_id = training_id.map_err(|e| format!("Error pulling worker trainings: {}", e))?;
// get training from library
let training = match TRAINING_LIB.with_lock(|lib| lib.get(&training_id.to_string())) {
// if training is already in library, return it
Some(training) => training,
// if training is not in library, pull from database and add to library
None => {
let training = Training::pull_new(&training_id.to_string(), &conn)
.map_err(|e| format!("Error pulling worker trainings: {}", e))?;
let added_training = TRAINING_LIB.with_lock(|lib| {
match lib.add(&training_id.to_string(), training) {
Some(training) => Ok(training),
None => Err(format!("Error pulling worker trainings: training with id {} not found", training_id)),
}
}).map_err(|e| format!("Error adding training to library: {}", e))?;
added_training
}
};
}
the AI's solution looks much better, but I'd like to know how to approach something like this in the future so that i don't come up with such mangled mess
as in "What was the error in my thinking that made it come out like that"
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.