Get the latest tech news
A comparison of Rust’s borrow checker to the one in C#
Behold: the classic example of rust’s zero-cost memory safety… // error[E0597]: `shortlived` does not live long enough let longlived = 12; let mut plonglived = &longlived; { let shortlived = 13; plonglived = &shortlived; } *plonglived; …ported to C#: // error CS8374: Cannot ref-assign 'shortlived' to 'plonglived' because // 'shortlived' has a narrower escape scope than 'plonglived' var longlived = 12; ref var plonglived = ref longlived; { var shortlived = 13; plonglived = ref shortlived; } _ = plonglived; OK, so C# doesn’t share the Rust concept of “borrowing,” so it wouldn’t technically be correct to call this “borrow checking,” but in practice when people talk about “Rust’s borrow checker” they’re talking about all of the static analysis Rust does to ensure memory safety, for which I think this qualifies. When I first saw this feature in C# (and also Spans, ref structs, and stackalloc), I was blown away: where are all the angle brackets and apostrophes? How is it possible that I can write efficient and provably-safe code in C# without a degree in type theory? In this document I hope to briefly summarize my understanding of memory safety in C#, make direct comparisons between C# constructs and the corresponding Rust ones, and maybe shed some light on what trade-offs C# made exactly to get this so user-friendly.
In this document I hope to briefly summarize my understanding of memory safety in C#, make direct comparisons between C# constructs and the corresponding Rust ones, and maybe shed some light on what trade-offs C# made exactly to get this so user-friendly. In the process of adding the above features, C# needed to define rules around ref usage that would continue to ensure memory safety. A “ref safe context” is likely better-known to Rust programmers as a lifetime, the region of source text in which it is valid to access/use a reference.
Or read this on Hacker News