jojo
jojo

Reputation: 409

Cannot mutably borrow in a pattern guard [E0301]

unsafe fn get_sync_handle(pid: u32) -> Option<HANDLE>
{
    let raw_h = OpenProcess(SYNCHRONIZE, 0, pid as DWORD);
    match raw_h
    {
        x if x >= 0 as HANDLE => None,
        x => Some(x)
    }
}

src\lib.rs:411:19: 411:23 error: cannot mutably borrow in a pattern guard [E0301] src\lib.rs:411 x if x >= zero => None

Could someone explain to me cause of this error? While I know this is quite contrived example I don't understand why compiler complains, I'm not trying to modify anything, and raw_h itself is immutable.

Upvotes: 1

Views: 540

Answers (2)

Shepmaster
Shepmaster

Reputation: 430841

Here's a self-contained example:

type Handle = *mut ();

fn main() {
    let foo = 0 as Handle;
    match foo {
        x if x >= 0 as Handle => None,
        x                     => Some(x)
    };
}

Note the error message and where it points:

<anon>:6:19: 6:30 error: cannot mutably borrow in a pattern guard [E0301]
<anon>:6         x if x >= 0 as Handle => None,
                           ^~~~~~~~~~~

It's actually the "null" that is complained about. You can flip the check around, then there won't be any mutability in the match guard.

type Handle = *mut ();

fn main() {
    let foo = 0 as Handle;
    match foo {
        x if x as isize >= 0 => None,
        x                    => Some(x)
    };
}

Upvotes: 4

jojo
jojo

Reputation: 409

I already happened to find reason why it doesn't works. It's because retep998/winapi-rs which I'm using defines HANDLE as *mut c_void, casting to usize solves problem.

Upvotes: 0

Related Questions