#How to conditionally return a reference or stop borrowing

10 messages · Page 1 of 1 (latest)

tribal radish
#

Hi, the borrow checker complains about the following (simplified) code:

fn get_true<'a>(vec: &'a mut Vec<bool>, index: usize)-> &'a bool{
    let my_bool: &bool = vec.get(index).unwrap();

    if *my_bool{
        return my_bool;
    }

    vec[index] = true;
    return vec.get(index).unwrap();    
}

Essentially I want to return a reference to an element of a vec. If a condition is met I want to return it immediately, otherwise I want to modify the vec and return something else. This seems like it should it should be able to stop borrowing after checking my condition but instead I get cannot borrow `*vec` as mutable because it is also borrowed as immutable and returning this value requires that `*vec` is borrowed for `'a`

near ingot
#

-errors

potent kindleBOT
#

If you're getting large or confusing errors please post the full error message from cargo check in a code block instead of the errors in your IDE so that we can understand your problem better:

```rust
// error from cargo check here
```

near ingot
#

im unsure what exactly I can change because this simplified example is likely a lot more flexible than what youre doing

#

note that I think in terms of the borrow checker, the reference you return is going to be treated like a mutable reference because its origin is from a mutable reference

brittle moat
#

It is, yes

brittle moat
tribal radish
tribal radish