logoalt Hacker News

Ygg2yesterday at 6:22 AM3 repliesview on HN

> True, but unsafe let's you conjure up any lifetime you want

The only thing unsafe does is let you have an unbounded lifetime. As I said, it doesn't check those:

   fn get_str<'a>(s: *const String) -> &'a str {
       unsafe { &*s }
   }

https://doc.rust-lang.org/nomicon/unbounded-lifetimes.html

> if you generously sprinkle pointer dereferences in unsafe code, you effectively disable the protection provided by the borrow checker

You don't disable anything. You wrote a "trust me compiler" block, and compiler trusted you.

Rust won't ever protect from all possible problems, just the ones the compiler handles.


Replies

geonyesterday at 2:10 PM

> You don't disable anything. You wrote a "trust me compiler" block, and compiler trusted you.

That’s the same thing.

zombotyesterday at 7:53 AM

What's the point of using Rust in the first place when you disable the compiler feature that protects you the most?

show 3 replies
adwnyesterday at 11:38 AM

> The only thing unsafe does is let you have an unbounded lifetime.

No, you're wrong: You can create any lifetime. Proof:

    fn oof<'desired>(x: &u32) -> &'desired u32 {
        let ptr = x as *const u32;
        unsafe { &*ptr }
    }
This will take a reference and return it with any lifetime specified by the caller.

> You don't disable anything.

I said "effectively disable". For example:

fn trust_me_bro<'a>(x: mut u32) -> &'a mut u32 { unsafe { &mut x } }

    fn main() {
        let mut x = 1_u32;
        let reference_a = &mut x;
        let reference_b = trust_me_bro(reference_a);
        *reference_b = 2;  -- Whoops
        println!("reference_a: {reference_a}  reference_b: {reference_b}");
    }
After the call to trust_me_bro, two aliasing, mutable references exist simultaneously. This would usually be prevented by the borrow checker, but the unsafe code has effectively disabled it.
show 1 reply