Borrowing and Ownership

Timon Gehr timon.gehr at
Mon Oct 28 23:01:03 UTC 2019

On 28.10.19 02:26, jmh530 wrote:
> On Sunday, 27 October 2019 at 22:36:30 UTC, Timon Gehr wrote:
>> [snip]
>> The main drawback of this proposal is that it doesn't separate control 
>> of lifetime and control of aliasing, doing so would however require 
>> adding another type qualifier and does not have precedent in Rust.
> I'm a little confused by this. What type qualifier would need to be 
> added and having what properties?

In the current language, `scope` only restricts lifetime. In particular, 
it is used to ensure addresses do not escape. What's missing is a way to 
ensure that there is either some number of `immutable` or exactly one 
mutable reference to your data, so with separate qualifiers you'd add a 
qualifier for that, leaving `scope` as-is. This would leave open the 
possibility to express functions that take multiple scoped references to 
the same location.

E.g., one major problem I see with following DIP 1021 to its logical 
conclusion is that you won't be able to easily express some standard 
idioms anymore, like swapping two entries of an array:

swap(a[i],a[j]); // error, a[i] and a[j] might alias

In a language where `scope` and `ref` do not _imply_ absence of mutable 
aliasing, you can still implement the `swap` function such that the code 
above compiles. I imagine the most annoying way the compiler error above 
will surface is if your algorithm actually guarantees that the two 
swapped values are different, but the compiler frontend cannot prove 
that this is the case.

Note that I don't necessarily like the direction that D is going with 
DIP 1021. I wrote the OP because Walter asked me to share my thoughts on 
borrowing and ownership on the newsgroup and I wanted to present 
something that is concrete enough (if I make proposals that are too 
abstract, Walter does not parse them) and compatible with the accepted 
DIP 1021.

For someone who is happy with writing @safe code using D's built-in GC, 
such restrictions will be quite off-putting.

However, Rust is in the same boat, see:
For built-in slices, they work around the problem using a Go-esque type 
system restriction workaround, i.e., they express references as integers 
representing indices, and of course that only addresses this specific case.

More information about the Digitalmars-d mailing list