The other difference is that *ptr = val;
promises the compiler that there will not be any other references to *ptr
in existence across this statement, whereas ptr.write(val)
makes no such promise.
This doesn't matter so much in this example, but if instead of val
, you have foo(ptr)
, you're at risk of a surprise, since foo
might also dereference ptr
, and if it does, you now have two references to *ptr
in existence at the same time. And you're most likely to get this wrong with static mut
, since I can create a new reference to any visible static mut
inside foo()
.
In contrast, if you do ptr.write(foo(ptr))
, and foo(ptr)
only ever uses ptr.read
and ptr.write
, you will never have accidental UB from two references existing at once, because you never have one reference, let alone two.