When defining datastructures, I sometimes need an unsafe
method of accessing the structure, which can break the invariants of the structure. I really like using unsafe
to support this, but some other developers I work with think unsafe
should only be used for code which can cause memory-corruption/crashes. Therefore I'd like to suggest the ability to introduce new "types" of unsafe
in packages, which both lets devs be more specific about what is unsafe.
I'm happy to discuss real examples, but for now let's consider a simple fake example, a pair of integers which have to be different: struct DisjointPair { a: usize, b: usize }
. Occasionally, for efficiency, I need raw mutable access to a
, so I currently write:
impl DisjointPair {
unsafe fn get_a(&mut self) -> &mut usize
{ &mut self.a }
}
I suggest we instead write something like (I haven't thought of sensible parsable notation)
unsafe disjoint; // Define 'disjoint' as a new type of unsafe
impl DisjointPair {
unsafe(disjoint) fn get_a(&mut self) -> &mut usize
{ &mut self.a }
}
Then in use we would write: unsafe(disjoint) { val.get_a() ... }
. Standard unsafe
would not imply unsafe(disjoint)
.