Skip to content

rustc refuses to compile const function due to potential drops even when nothing is being dropped #115403

Closed
@TheNeikos

Description

@TheNeikos

I tried this code:

use core::marker::PhantomData;
use std::sync::Arc;
struct Foo<T> {
    drop_value: Arc<u32>,
    pd: PhantomData<fn(T)>,
}

impl<T> Foo<T> {
    const fn convert<R>(self) -> Foo<R> {
        let Foo { drop_value, pd: _ } = self;

        Foo {
            drop_value,
            pd: PhantomData,
        }
    }
    
    const fn convert2<R>(self) -> Foo<R> {
        Foo {
            drop_value: self.drop_value,
            pd: PhantomData,
        }
    }
}

I expected to see this happen: It compiles

Instead, this happened:

Compiling playground v0.0.1 (/playground)
error[[E0493]](https://doc.rust-lang.org/nightly/error_codes/E0493.html): destructor of `Foo<T>` cannot be evaluated at compile-time
  --> src/lib.rs:9:25
   |
9  |     const fn convert<R>(self) -> Foo<R> {
   |                         ^^^^ the destructor for this type cannot be evaluated in constant functions
...
16 |     }
   |     - value is dropped here

For more information about this error, try `rustc --explain E0493`.
error: could not compile `playground` (lib) due to previous error

Meta

This errors on stable 1.72 as well as on nightly-2023-08-30.

This is maybe the same as #109427, but since that is about patterns, and this is not, I thought the independent report is justified.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)A-destructorsArea: Destructors (`Drop`, …)C-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions