Is this NLL bug or am i wrong?

a netizen asked in rustcc.cn, and I was curious.
The following code could not be compiled,error mess is "num does not live long enough"

use std::cell::RefCell;
pub fn max_level_sum(num: RefCell<Option<i32>>) {
    let num = num;
    if let None = *num.borrow() {
        println!("none");
    }
}

but here is move right?
how to fix it?
just add ";" at end of line of 6,like this:

use std::cell::RefCell;
pub fn max_level_sum(num: RefCell<Option<i32>>) {
    let num = num;
    if let None = *num.borrow() {
        println!("none");
    };
}

it's strange.
could someone explain about it?
thanks!

1 Like

I don't think this has anything to do with NLL.

The *num.borrow() statement creates a temporary Ref<Option<i32>> and then automatically dereferences it. Your problem is the reference you get from * can't outlive the temporary, so hoisting the num.borrow() into a local variable will broaden the Ref<Option<i32>>'s lifetime.

use std::cell::RefCell;

pub fn max_level_sum(num: RefCell<Option<i32>>) {
    let num = num;
    
    let num_ref = num.borrow();
    
    if let None =  *num_ref {
        println!("None")
    }
}
1 Like

oh~,i see, understand,thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.