• JackbyDev@programming.dev
    link
    fedilink
    English
    arrow-up
    1
    ·
    3 hours ago

    Doesn’t Rust’s safety guarantees mean automatic reference counting? Or am I misunderstanding. I guess it means more like happening dynamically at runtime.

    • calcopiritus@lemmy.world
      link
      fedilink
      arrow-up
      1
      ·
      2 hours ago

      You can reference count, but you must do so explicitly, just like in C++ you have to explicitly use std::shared_ptr, in rust you must explicitly use std::rc::Rc.

      Rusts’ memory safety is managed at compile time, that’s what the borrow checker does. It enforces a strict set of simple rules that guarantee at compile time that all the references are valid when they are used. This means that there is no runtime cost.

      Q: “Why would you use Rc then? It would only introduce runtime overhead that is not needed because rust already checked that the program is correct”

      A: the borrow checker ensures that your program is valid. However, not all valid programs are allowed by the borrow checker. That is what unsafe is for. unsafe allows you to skip some rust safety features if you want to make a program that is valid but rejected by the “safe” rust compiler. Rc uses unsafe internally to expose an API that is safe, but allows you to do things that would normally be rejected by rust.

      Of course, the borrow checker is not all the safety features of rust. There are some safety features that actually do have runtime checks.

      For example, you can try to access invalid memory by reading out of the bounds of a buffer/array. Most of the time, it is impossible/impractical to solve for this at compile time. Therefore, a bounds check is done on every array access, if the check fails, the program crashes. That check is done at run time. Many times the compiler will optimize those checks, but sometimes they just cannot be optimized out.