panic when trying to unwrap `Weak<RefCell>`

  Kiến thức lập trình

I have this snippet of code. when I’m trying to unwrap block and access its inner value, which is of type Weak<RefCell<T>> I get a panic.

fn to_opcode_from_branch(branch: Branch) -> Option<OpCode> {
    match branch {
        Branch::CJump { block } => {
            // unwrapping and copying inner value of block
            let label = Rc::into_inner(block.upgrade().unwrap()) // NOTE: panic happens here!!
                .unwrap()
                .into_inner()
                .instructions[0]
                .clone();

            if let PseudoInstruction::Label { label } = label {
                Some(OpCode::Jump { label })
            } else {
                eprintln!("unexpected behavior: label not found at the beginning of the block.");
                exit(1);
            }
        }
    _ => None,
    }
}

I looked around and figured out that reading a weak pointer in rust drops its pointer (am I correct on this one? please correct me if not). so if it’s not possible to read a weak pointer directly, what is the right way to right way to access content inside Weak<RefCell<T>>?

LEAVE A COMMENT