How to efficiently write and check unsafe code?

I read this, Stacked Borrows Implemented, and I find it difficult to understand...

I think it's important to be familiar with stacked borrow and Miri usage before writing unsafe code, right? If not, how to effectively write and check unsafe code?

There is not a single trick to knowing how to write correct unsafe code. The two best pieces of advice I can give you is:

  1. Avoid writing unsafe as much as possible. Ordinary projects pretty much don't need any unsafe at all unless they are dealing with FFI.
  2. Keep it as simple, small-impact, and structured as possible. For example, pointer casts that are equivalent with transmuting between primitives are usually fine, but complicated data structure chasing is not. If you have a resource to manage manually, wrap it in an RAII guard and expose only a safe API, etc.
1 Like

The reason I want to understand unsafe is that I'm studying the implementation of linked lists at Layout - Learning Rust With Entirely Too Many Linked Lists. I apologize for not mentioning this earlier.
This might be one of the rare occasions for me to work with unsafe code.

Note that Stacked Borrows isn't stable. Neither is Tree Borrows. In regard to the latter, I found this document linked by @quinedot good to get an understanding:

Unfortunately, it seems not totally clear (yet) how certain rules will be standardized. See that other thread for some hints in regard to how conservative assumptions can help to avoid potential undefined behavior (UB).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.