Confused about drop memory,why does it can work?

Btw, never transmute &mut to & & to &mut (got the order wrong there). You must only do this through an UnsafeCell (or a safe abstraction like Cell, RefCell, Mutex, RwLock). The problem is, that you'll currently never see this being problematic in single-threaded code due to a bug in LLVM having forced Rust to turn off noalias optimization, i.e. every &mut behaves like &UnsafeCell<_>.

yeah,i use crossbeam's AtomicCell and Arc and async-std's RwLock, thanks for your advice

Unsafe Rust can certainly be dangerous if you don't know what you're doing. The point of unsafe is that you must uphold the guarantees that safe Rust ensures. I would suggest you should have a good grasp of safe Rust and have read the nomicon before writing unsafe Rust, so that you know what those guarantees are and what is and isn't safe to do in unsafe Rust.

2 Likes

oh!i have read this book before, but at not long after I started learn rust.something i already forget.
i will read it again,i think it will more impressive than before.
helpful advice,thanks bro

Using unsafe is generally an advaced topic. Don't use unsafe unless you know you need it (i.e. unless you can't do something with safe code), and only if you have a good understanding of low-level details like memory management.

Most of the time, using unsafe is a very last resort or for excessively clever performance optimizations. Safe Rust is expressive enough to write 99.99% of the code you might want to write – and while you are not well-versed in low-level, systems programming concepts (think of it as something to the extent of being an advanced C user, for instance), basically don't even think about unsafe. You won't have a legitimate need for it.

Go with safe code – the worst that can happen is that some of the code you write will not be maximally optimal. But you get compiler-verified correctness, and that matters a lot more.

7 Likes

yes,the stable and correct is more import