Make `#[may_dangle]` more functional

1. Allow #[may_dangle] to appear before the generic lifetime of the structure generates a declaration.

struct Foo<#[may_dangle] 's> {...}

If this is done, the dangle of the lifetime 's will not make the type Foo<'s> also become dangle.

If this is done, then the use of the lifetime 's within the structure Foo can only be done using the method of #[may_dangle].

struct Bar<#[may_dangle] 's> {...}
struct Foo<#[may_dangle] 's> {
    bar: Bar<'s>,
}

Normal use will be rejected by the compiler:

struct Foo<#[may_dangle] 's> {
    bar: &'s i32,
//       ^^^^^^^ &'s i32 not allow 's dangle
}

The survival time of a structure is independent of its lifetime 's.

Foo<'s>: 'static

2. Allow #[may_dangle] to modify any type

Make #[may_dangle] &'s i32 a legal type:

fn foo<#[may_dangle] 's>(x: #[may_dangle] &'s i32) {...}

Values with type #[may_dangle] T can only be copied (if T can be copied) and moved, and cannot read members or call methods.

Therefore, x cannot be dereferenced.

Types with #[may_dangle] modification can also serve as member types of structural entities.

struct Foo<#[may_dangle] 's> {
    bar: #[may_dangle] &'s i32,
}

The survival time of #[may_dangle] T is 'static

#[may_dangle] T: 'static

3. Using a value of #[may_dangle] will not result in an extension of the lifetime

fn foo<#[may_dangle] 's>(x: #[may_dangle] &'s i32) {...}

let a: #[may_dangle] &i32;
{
    let x = 1;
    a = &x;
}
foo(a);

These are part of the specific design and implementation of


1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.