Borrowing and Ownership

jmh530 john.michael.hall at
Tue Oct 29 21:46:55 UTC 2019

On Monday, 28 October 2019 at 23:01:03 UTC, Timon Gehr wrote:
> [snip]
> 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.

I have some follow up comments after thinking about your reply.

One key thing about Rust's borrow checker is that even when you 
make a mutable borrow of mutable data, then you cannot modify the 
original data while the borrow is in effect. So for instance, the 
follow code does not compile in Rust

fn main() {
     let mut x = 1;
     let y = &mut x;
     x += 1;
     *y += 1;
     println!("{}", x);

You need to remove the line that `x += 1` for it to compile. The 
D version runs with no issues:

import std.stdio : writeln;

void main() {
     int x = 1;
     int* y = &x;
     x += 1;
     *y += 1;

So this "single mutable reference" that you discuss is not the 
same thing as saying there must be no more than one pointer to 
some variable. It's really that there is only one way to access 
some variable (perhaps similar to iso in Pony?). If you have a 
mutable pointer to the variable, then you cannot access it 
directly while the pointer is active.

Similarly, when Rust has an immutable borrow on mutable data, 
then it not only prevents mutable borrows of the same data but it 
also also prevents modifying the data directly. However, a D 
const pointer would still allow a variable to be changed through 
direct access if the data is mutable or through some other 
mutable pointer. Even if you dis-allow mutable pointers when 
there is a const pointer, a variable with const pointers to it 
would still be able to be changed through direct access.

So in this sense, not only would you need some type qualifier to 
ensure that you can either have one mutable pointer or many const 
pointers, but also you would need to ensure that there is no 
direct access to the underlying data when those pointers are 
valid. At least if you want to be consistent with Rust's approach.

For that reason, I would also not be surprised that whatever type 
qualifier you would favor would also need to either imply scope 
or be closely tied to scope somehow to guarantee safety. I don't 
know that for sure though.

More information about the Digitalmars-d mailing list