[Resolved] Part of the code is not always executed

Hi to all,
I'm a little bit confused by the issue I face.
I wrote a function within which part of is code is not always executed and I don't understand why...

The function looks like that:

pub fn function (args: &str) -> Result<()> {
    // the beginning of the function is always executed
    let values = vec!["value1", "value2"];
    for value in values {
         println!("{}", value);
    // what is inside the for loop is always executed
    }
    // what is after the for loop may not be executed
    println!("{:?}", values);
    // the caller of the function reveives the Result
    Ok(())
}

The code compiles correctly.
The code executes without any panic.

What am I missing? is there any condition for the function to exit before the end of the execution?

Thanks in advance for your support.

Are you sure your function doesn't exits early under some condition with a return statement somewhere? Or is the function you presented really the function you are executing?

The example you've given does not compile correctly: Rust Playground

If I fix it by changing for value in values { to for value in &values {, the function always executes the code after the for loop.

I'm guessing that whatever you've reduced this from has a ?, a return, or some other early return inside the for loop, and thus is returning early from the function.

4 Likes

Hi to all,

Thank you for your feedback.

@farnz : you're right. I missed an '?' operator inside the function that provoked an early exit from inside the function.

Thanks again

1 Like

Hi @pgi , welcome to the forum! When a question is resolved, please select the checkbox at the bottom of the message that resolved it, and then it will show as answered in the message list for everyone to see. You don't need to add "[Resolved]" to the title.

2 Likes

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.