Search code examples
rustreturnlazy-static

Why does this return statement cause an error but the return expression doesn't in Rust?


I'm confused why this code works below:

lazy_static! {
        static ref TSS: TaskStateSegment = {
            let mut tss = TaskStateSegment::new();
            tss.interrupt_stack_table[DOUBLE_FAULT_IST_INDEX as usize] = {
                const STACK_SIZE: usize = 4096 * 5;
                static mut STACK: [u8; STACK_SIZE] = [0; STACK_SIZE];
    
                
                let stack_start = VirtAddr::from_ptr(unsafe {&STACK});
                let stack_end = stack_start + STACK_SIZE;
                
                
                stack_end        
            };
            tss
        };
    }

While on the contrary, this code doesn't:

lazy_static! {
    static ref TSS: TaskStateSegment = {
        let mut tss = TaskStateSegment::new();
        tss.interrupt_stack_table[DOUBLE_FAULT_IST_INDEX as usize] = {
            const STACK_SIZE: usize = 4096 * 5;
            static mut STACK: [u8; STACK_SIZE] = [0; STACK_SIZE];

            
            let stack_start = VirtAddr::from_ptr(unsafe {&STACK});
            let stack_end = stack_start + STACK_SIZE;
            
            return stack_end
                    
        };
        tss
    };
}

It's that specific return that causes an error for Rust analyzer and it confuses me. I typically use lots of explicit returns because when I code I prefer to be explicit rather than implicit but something about this error confused me because I don't understand why one would cause an error and the other wouldn't?


Solution

  • return is for returning early from a function or closure. The {} block is not a function, so replacing the block's final expression with a return statement does not create semantically equivalent code.

    I typically use lots of explicit returns because when I code I prefer to be explicit rather than implicit

    Your code will be rejected by most Rust linters, then. They will flag return as the last statement of a function as redundant. return is for early returns.