Why can we use Arc without unsafe?


I’m still learning Rust.
While reading this intro, I have a question:
if Arc is Implemented by unsafe, why we dont need to use unsafe when using Arc module?

If Rust makes it impossible to unsafely share data between threads, and Rust is written in Rust, then how does it implement concurrent types like Arc and Mutex? The answer: unsafe.

As I learned in TheBook.

In both unsafe functions and unsafe blocks, Rust will let you do three things that you normally can not do. Just three. Here they are:

  1. Access or update a static mutable variable.
  2. Dereference a raw pointer.
  3. Call unsafe functions. This is the most powerful ability.

So Arc::New() is not a unsafe function?
But I imagine that Arc should use some unsafe magic to implement itself, how could it not be unsafe function?


An unsafe function is allowed to do unsafe things, but in turn is also unsafe to call. An unsafe {} block however allows you to do unsafe things inside it but without requiring that the function be unsafe.unsafe {} is the boundary between safe and unsafe, where you promise to the Rust compiler that whatever is inside that block will uphold Rust’s invariants so Rust can allow safe code to use it. The implementation for Arc has a lot of unsafe {} blocks inside of it that do scary unsafe things, but they are all carefully verified by humans to ensure that they will uphold Rust’s invariants and thus are safe to use.


OK. I got it! Thanks a lot!


There’s an interesting blog post about using unsafe to build safe abstractions: http://smallcultfollowing.com/babysteps/blog/2016/05/23/unsafe-abstractions/