Currently, the lifecycle is continuous, and borrowing using the lifecycle must not survive beyond its lifespan (ignore dropck_eyepatch).
If we want to store a mutable pointer at the same time, we have to use RefCell or UnsafeCell to do this.
Now, propose a new lifetime form that will allow for discontinuous availability of its resources.
The method is to add a keyword with a tentative name of discontinuity
, which will cause the following code to compile
let mut x = 1;
let a = #[discontinuity] &mut x;
let b = #[discontinuity] &mut x;
*a = 1;
*b = 2;
In the structure:
struct Foo<#[discontinuity] 'a> {
r: &'a i32,
}
To dereference a discontinuous borrowing, it is necessary to prove that it is currently valid:
fn as_mut_ref<#[discontinuity] 's, 'a>(r: &'s mut i32) -> &'a mut i32
where 's: 'a {
r
}
fn read_discontinuity_ref<#[discontinuity] 's, 'a>(r: &'s i32) -> i32
where 's: 'a {
*r
}
fn read_discontinuity_ref<#[discontinuity] 's>(r: &'s i32) -> i32
where 's: 'function_call { // 'function_call: Is it valid when call function, or is it a different name?
*r
}
Otherwise, it cannot be dereferenced:
fn err_read_discontinuity_ref<#[discontinuity] 's>(r: &'s i32) -> i32 {
*r
// ^^ Compile error: 's maybe dangling
}
Borrowing with discontinuous lifetime and 'static
survival time.
fn box_any<#[discontinuity] 's>(r: &'s i32) -> Box<dyn Any + 'static> {
Box::new(r)
}
Add a discontinuous lifetime constant of 'dangle
, just like 'static
, but the semantics are completely opposite.
fn dangle_ref<#[discontinuity] 's>(r: &'s i32) -> &'dangle i32 {
r
}
fn dangle_ref2() -> &'dangle i32 {
let x = 1;
#[discontinuity] &mut x
}
Perhaps keywords and related language design still need to be discussed, but I believe discontinuous lifetime is complete.
It seems that quite a few people have asked me to provide a definition of discontinuous lifetime
Informally speaking:
- A discontinuous lifetime is the sum of multiple ordinary lifetime.
- Discontinuous lifetime borrowing can only be dereferenced when there is any one valid internal ordinary lifetime.