# Idea: Discontinuous lifetime and its borrowing

**URL:** <https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699>\
**Category:** language design\
**Created:** [April 18, 2023, 12:40am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699 "2023-04-18T00:40:21Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Qsh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/qsh/32/10418_2.png) [@Qsh](https://internals.rust-lang.org/u/Qsh)\
**Post date:** [April 18, 2023, 12:40am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/1 "2023-04-18T00:40:21Z")

</div>

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

```rust
let mut x = 1;
let a = #[discontinuity] &mut x;
let b = #[discontinuity] &mut x;
*a = 1;
*b = 2;

```

In the structure:

```rust
struct Foo<#[discontinuity] 'a> {
    r: &'a i32,
}

```

To dereference a discontinuous borrowing, it is necessary to prove that it is currently valid:

```rust
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:

```rust
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.

```rust
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.

```rust
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.

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/scottmcm/32/2355_2.png) [@scottmcm](https://internals.rust-lang.org/u/scottmcm)\
**Post date:** [April 18, 2023, 1:29am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/2 "2023-04-18T01:29:14Z")

</div>

> [@Qsh](#):
>
> The method is to add a keyword with a tentative name of `discontinuity`, which will cause the following code to compile
> 
> ```rust
> let mut x = 1;
> let a = #[discontinuity] &mut x;
> let b = #[discontinuity] &mut x;
> *a = 1;
> *b = 2;
> 
> ```

What _exactly_ are the rules you're proposing here?

What if `x` were a vector and it's reallocated via `a` before the `b` reference to an element is used?

You should probably include some examples that aren't trivially translatable to `Cell`s.

---

<div class="post-metadata">

**Author:** ![Qsh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/qsh/32/10418_2.png) [@Qsh](https://internals.rust-lang.org/u/Qsh)\
**Post date:** [April 18, 2023, 1:43am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/3 "2023-04-18T01:43:58Z")

</div>

> [@scottmcm](#):
>
> You should probably include some examples that aren't trivially translatable to `Cell`s.

```rust
struct B<#[discontinuity] 'a> {
    a: &'a mut Vec<i32>,
}
let mut a = Vec::new();
let b = B { a: #[discontinuity] &mut a };

a.push(1);
b.a.push(2);
a.push(3);

```

It is equivalent to using RefCell, but the latter introduces additional overhead (even if the compiler eliminates such simple situations)

```rust
struct B<'a> {
    a: &'a RefCell<Vec<i32>>,
}
let a = RefCell::new(Vec::new());
let b = B { a: &a };

a.borrow_mut().push(1);
b.a.borrow_mut().push(2);
a.borrow_mut().push(3);

```

---

<div class="post-metadata">

**Author:** ![Qsh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/qsh/32/10418_2.png) [@Qsh](https://internals.rust-lang.org/u/Qsh)\
**Post date:** [April 18, 2023, 1:48am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/4 "2023-04-18T01:48:02Z")

</div>

> [@scottmcm](#):
>
> What _exactly_ are the rules you're proposing here?

Discontinuous borrowing refers to resources that may not be available now but may be available for certain time periods in the future. For variable mut borrowing, this does not violate the alias rule. Although there are multiple pointers to the same location at the same time, only one is still valid at the same time, but they can exhibit alternation.

---

<div class="post-metadata">

**Author:** ![Qsh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/qsh/32/10418_2.png) [@Qsh](https://internals.rust-lang.org/u/Qsh)\
**Post date:** [April 18, 2023, 1:54am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/5 "2023-04-18T01:54:06Z")

</div>

> [@scottmcm](#):
>
> What if `x` were a vector and it's reallocated via `a` before the `b` reference to an element is used?

```rust
struct B<#[discontinuity] 'a> {
    a: &'a mut Vec<i32>,
}
let mut a = Vec::new();
let b: B<#[discontinuity] '1> = B { a: #[discontinuity] &mut a };

a.push(1);

// ’1 valid
b.a.push(2);
// '1 invalid

a.push(3);

// '1 valid again
b.a.push(2);
// '1 invalid again

 a.push(3);

```

The lifetime is the coloring on the Control flow graph. Now the coloring does not need to be continuous, and the creation of borrowing does not need to be currently valid.

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jrose/32/9591_2.png) [@jrose](https://internals.rust-lang.org/u/jrose)\
**Post date:** [April 18, 2023, 2:19am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/6 "2023-04-18T02:19:58Z")

</div>

I think scottmcm was referring to something like this:

```rust
let mut x = vec![1];
let a = #[discontinuity] &mut x;
let b: &mut [i32] = #[discontinuity] x.as_mut();
a.push(0); // reallocates storage
b[0] = 2; // what happens here? and what is the rule that makes it so?

```

---

<div class="post-metadata">

**Author:** ![quinedot](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/quinedot/32/7294_2.png) [@quinedot](https://internals.rust-lang.org/u/quinedot)\
**Post date:** [April 18, 2023, 2:22am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/7 "2023-04-18T02:22:03Z")

</div>

> [@Qsh](#):
>
> It is equivalent to using RefCell,

A compile-time check literally can't be equivalent to the run-time check of a `RefCell`, as you can reduce the halting problem to "does this `RefCell` usage panic?".

So you need to explain exactly which cases would be covered (and preferably how that's implemented and why it's sound).

What's an example that isn't trivially rewritten to Rust that compiles today?

---

<div class="post-metadata">

**Author:** ![Qsh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/qsh/32/10418_2.png) [@Qsh](https://internals.rust-lang.org/u/Qsh)\
**Post date:** [April 18, 2023, 2:31am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/8 "2023-04-18T02:31:24Z")

</div>

> [@jrose](#):
>
> ```rust
> let b: &mut [i32] = #[discontinuity] x.as_mut();
> a.push(0); // reallocates storage
> b[0] = 2; // what happens here? and what is the rule that makes it so?
> 
> ```

This is obviously wrong, and the reason for rejecting it can be

`let b: &mut [i32] = #[discontinuity] x.as_mut();`

or say

`let b: &mut [i32] = #[discontinuity] &mut x.as_mut();`

`as_mut` (and `get`) should return continuous borrowing, even if we can continue to make discontinuous borrowing on this continuous borrowing, and this continuous borrowing should not conflict with other borrowing methods

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jrose/32/9591_2.png) [@jrose](https://internals.rust-lang.org/u/jrose)\
**Post date:** [April 18, 2023, 2:53am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/9 "2023-04-18T02:53:11Z")

</div>

I see. So `#[discontinuity]` can’t be used with return values, because then the compiler wouldn’t know how to “restart” the borrow? I suppose that works, but then I’m less sure of the motivation. It seems like non-lexical borrows already let you do this, so you’re just saving from having to write `let a = &mut x;` a second time. Which is convenient, I guess.

---

<div class="post-metadata">

**Author:** ![Qsh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/qsh/32/10418_2.png) [@Qsh](https://internals.rust-lang.org/u/Qsh)\
**Post date:** [April 18, 2023, 3:02am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/10 "2023-04-18T03:02:01Z")

</div>

I think an example is:

```rust
fn as_mut<#[discontinuity] 'a: 'b, 'b, T>(x: &'a mut Vec<T>) -> &'b mut [T] {
    &mut *x
}

let mut x: Vec<i32> = vec![1];
let a/* &#[discontinuity] '1 mut Vec<i32> */ = #[discontinuity] &mut x; // (in this line, '1 can be invalid)
let b/* &#[discontinuity] '2 mut Vec<i32> */ = #[discontinuity] &mut x; // (in this line, '2 can be invalid)
let b_slice/* &'3 mut [i32] */ = as_mut(b); // '2 '3
// Error: ^^^^^^^ dissatisfaction '2: '3

a.push(0); // '1 '3
b_slice[0] = 2; // '2 '3

```

---

<div class="post-metadata">

**Author:** ![Qsh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/qsh/32/10418_2.png) [@Qsh](https://internals.rust-lang.org/u/Qsh)\
**Post date:** [April 18, 2023, 3:06am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/11 "2023-04-18T03:06:14Z")

</div>

> [@jrose](#):
>
> It seems like non-lexical borrows already let you do this,

This indicates that my design is reasonable. 😀

But obviously not completely achieving my goal, because

> [@jrose](#):
>
> you’re just saving from having to write `let a = &mut x;`

This is unacceptable! Because this damages the packaging, if we need a wrapper, we cannot borrow it again every time.

---

<div class="post-metadata">

**Author:** ![Qsh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/qsh/32/10418_2.png) [@Qsh](https://internals.rust-lang.org/u/Qsh)\
**Post date:** [April 18, 2023, 3:09am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/12 "2023-04-18T03:09:02Z")

</div>

A complaint I heard (though there was something wrong with it)

> 前段时间有个大作业不限制语言，于是就想用rust写一下顺便熟悉一下rust，然后习惯性地套上写C++时的代码习惯：
> 
> ```rust
> void foo() {
> A a();
> B b(&a);
> C c(&a, &b);
> // a, b, c干活balabala
> }
> 
> ```
> 
> 然后问题来了，rust不准存在多个可变引用，即使这是个单线程程序，所以只好`Box<RefCell<>>`满天飞，用起来满处都是`borrow`，最后忍无可忍还是换回了C++11，感觉脑子被rustc强奸了一样（或许我并不适合写rust吧）。
> 
> 作者：icysky 链接：[C++20 vs Rust，谁胜谁败？ - 知乎](https://www.zhihu.com/question/470324696/answer/2250347743) 来源：知乎 著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。

---

<div class="post-metadata">

**Author:** ![quinedot](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/quinedot/32/7294_2.png) [@quinedot](https://internals.rust-lang.org/u/quinedot)\
**Post date:** [April 18, 2023, 3:12am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/13 "2023-04-18T03:12:07Z")

</div>

I don't understand what that's trying to convey (something not permitted in your idea?), but it's still trivially rewritten to something that compiles today.

```rust
    let mut x: Vec<i32> = vec![1];
    x.push(0);
    x[0] = 2;

```

What's a motivating case that warrants the added complexity?

> [@Qsh](#):
>
> This is unacceptable! Because this damages the packaging, if we need a wrapper, we cannot borrow it again every time.

Why not?

```rust
    a.push(1);

    let b = B { a: &mut a };
    b.a.push(2);

    a.push(3);

    let b = B { a: &mut a };
    b.a.push(2);

```

---

<div class="post-metadata">

**Author:** ![Qsh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/qsh/32/10418_2.png) [@Qsh](https://internals.rust-lang.org/u/Qsh)\
**Post date:** [April 18, 2023, 3:13am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/14 "2023-04-18T03:13:46Z")

</div>

Because the creation of the wrapper may involve other tedious tasks, repeated creation is indeed unacceptable.

---

<div class="post-metadata">

**Author:** ![zirconium-n](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/zirconium-n/32/9078_2.png) [@zirconium-n](https://internals.rust-lang.org/u/zirconium-n)\
**Post date:** [April 18, 2023, 6:24am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/15 "2023-04-18T06:24:53Z")

</div>

实话说我不建议看任何知乎上的关于Rust或者C++的讨论。

> [@Qsh](#):
>
> Because the creation of the wrapper may involve other tedious tasks, repeated creation is indeed unacceptable.

You need to provide a concrete example. Code repetition itself is not unacceptable.

---

<div class="post-metadata">

**Author:** ![Qsh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/qsh/32/10418_2.png) [@Qsh](https://internals.rust-lang.org/u/Qsh)\
**Post date:** [April 18, 2023, 7:47am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/16 "2023-04-18T07:47:12Z")

</div>

我只是早上刷到了 🤣，不过我觉得别的语言里确实比较常见

* * *

Consider a classifier for classifying items and placing them in corresponding containers

```rust
fn classifier(input: i32, odd: &mut Vec<i32>, even: &mut Vec<i32>) {
    if (input & 1) == 0 {
        even.push(input);
    } else {
        odd.push(input);
    }
}

```

We can use it like this:

```rust
let mut odd = Vec::new();
let mut even = Vec::new();
while let Some(input) = read() {
    classifier(input, &mut odd, &mut even);
    // use odd and even
}

```

Its classification method is written and needs to be re passed in every time.

* * *

Now that we have more classification projects, we need to create a wrapper for all containers:

```rust
struct ClassifierConfig<'s> {
    odd: &'s mut Vec<i32>,
    even: &'s mut Vec<i32>,
    prime: &'s mut Vec<i32>,
    positive: &'s mut Vec<i32>, 
}

fn classifier(input: i32, config: &mut ClassifierConfig<'_>) {
    todo!()
}

```

The configuration may be large. And it may contain some proprietary things, such as Strings. Duplicate creation is indeed unacceptable.

```rust
let mut odd = Vec::new();
let mut even = Vec::new();
let mut prime = Vec::new();
let mut positive = Vec::new();
let mut config = ClassifierConfig {
    ...
};
while let Some(input) = read() {
    classifier(input, &mut config);
    // use all
}

```

You may say that the classifier should have ownership of these containers, but unfortunately, perhaps the users of the containers also think the same?

Users of containers will also create their usage configurations for these containers, it may not want to know the specific content of the classifier with ownership, and recreating configurations is also unacceptable.

---

<div class="post-metadata">

**Author:** ![zirconium-n](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/zirconium-n/32/9078_2.png) [@zirconium-n](https://internals.rust-lang.org/u/zirconium-n)\
**Post date:** [April 18, 2023, 7:59am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/17 "2023-04-18T07:59:38Z")

</div>

Aren't `odd`/`even`/`prime`/`...` outputs instead of configs? You should not mix them with actual configs. Put configs that is time consuming to create in one struct, and put outputs in another struct.

And with you last example. You can just reborrow the inner pieces of `ClassifierConfig`.

```rust
let mut odd = Vec::new();
let mut even = Vec::new();
let mut prime = Vec::new();
let mut positive = Vec::new();
let mut config = ClassifierConfig {
    ...
};
while let input = read() {
    classifier(input, &mut config);
    let ClassifierConfig { odd, even, prime, positive } = &mut config;
    // use all
}

```

---

<div class="post-metadata">

**Author:** ![Qsh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/qsh/32/10418_2.png) [@Qsh](https://internals.rust-lang.org/u/Qsh)\
**Post date:** [April 18, 2023, 8:05am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/18 "2023-04-18T08:05:41Z")

</div>

> [@zirconium-n](#):
>
> You can just reborrow the inner pieces of `ClassifierConfig`.

Please note that the configuration of the container's users can also be very large.

> [@zirconium-n](#):
>
> `let ClassifierConfig { odd, even, prime, positive } = &mut config;`

Recreating usage configurations is also unacceptable.

* * *

> [@zirconium-n](#):
>
> Put configs that is time consuming to create in one struct, and put outputs in another struct.

This may indeed be a feasible approach, but the accepted container may require some verification and other work, and repeated creation can affect performance.

---

<div class="post-metadata">

**Author:** ![Qsh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/qsh/32/10418_2.png) [@Qsh](https://internals.rust-lang.org/u/Qsh)\
**Post date:** [April 18, 2023, 8:08am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/19 "2023-04-18T08:08:43Z")

</div>

In fact, I think the abuse of Cells has already reflected this.

I remember Actix had an argument about UnsafeCell before?

I believe that a discontinuous lifetime can avoid the use of a portion of Cells.

---

<div class="post-metadata">

**Author:** ![SkiFire13](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/skifire13/32/7579_2.png) [@SkiFire13](https://internals.rust-lang.org/u/SkiFire13)\
**Post date:** [April 18, 2023, 8:58am UTC](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699/20 "2023-04-18T08:58:11Z")

</div>

> [@Qsh](#):
>
> I believe that a discontinuous lifetime can avoid the use of a portion of Cells.

The way I see it, discontinuous lifetimes are just a fancy word for saying to the compiler that it could/should automatically reborrow a reference, which is however something you can already do manually without `Cell`s although maybe less ergonomically. If this wasn't what you intended then please provide us with a formal description of the feature you're proposing so that we can properly understand the feature you need.

[Next page](https://internals.rust-lang.org/t/idea-discontinuous-lifetime-and-its-borrowing/18699.md?page=2)
