Search code examples
rustunsafe

Why does this unsafe block return a unit type?


I haven't quite understood how unsafe and assignments work together. The following code gives me some error:

fn num() -> u64 {
    1;
}

fn test() -> u64 {
    let x = unsafe {
        num();
    };
    return x;
}

The error is:

src/main.rs:37:9: 37:10 note: expected type `u64`
src/main.rs:37:9: 37:10 note:    found type `()`

My real example is similar to this one.


Solution

  • Semicolons.

    fn num() -> u64 {
        1
    }
    
    fn test() -> u64 {
        let x = unsafe {
            num()
        };
        return x;
    }
    

    See also this answer about semicolons.