Change the code to handle an error without a change method signature?

I have a code:

 let mut res = vec![];
                    for mut pipe_cmd in piped {
                        pipe_cmd = pipe_cmd.into_iter().map(|el| interpolate_env(el)).collect();
                        pipe_cmd = expand_wildcard(&cwd, pipe_cmd);
                        pipe_cmd = expand_alias(&aliases, pipe_cmd);
                        res = call_process_piped(pipe_cmd.clone(), &cwd, &res, &child_env).unwrap();
                    }

It's compiled and runs great until call_process_piped returns error. I tried to modify the code like:

 let mut res = vec![];
                    for mut pipe_cmd in piped {
                        pipe_cmd = pipe_cmd.into_iter().map(|el| interpolate_env(el)).collect();
                        pipe_cmd = expand_wildcard(&cwd, pipe_cmd);
                        pipe_cmd = expand_alias(&aliases, pipe_cmd);
                        match call_process_piped(pipe_cmd.clone(), &cwd, res, &child_env) {
                            Ok(next_res) => { res = next_res; }
                            Err(err) => {eprintln!("error {err} in call {pipe_cmd:?}");break}
                        } 
                    }

But it stopped to compile complaining that res is consumed and can't be revived back in the Ok' branch. How can I change the code without changing call_process_piped` signature?

Actually, the difference between the two snippets is the borrow: &res becomes res. If this is intentional, then you should write res.clone() instead of only res, if call_process_piped takes a Vec<_, _> in input. The error occurs because res is moved at the first iteration of the loop. So you can't use it later (in the second iteration and the next ones, or in the match). You should clone it if the performance cost is acceptable, if it's not, then consider changing your call_process_piped function to take a borrow instead of take the ownership of the Vec.

By the way, can you please fix you identation. Would be more readable.

Thanks for the advise. Regarding the identation. I grabbed the code from the working system. I hope that AI could fix the identation problem, instead of wasting human time for that. But AI prefers more complex task too.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.