How to take ownership of a field without running destructor in const context?

⚓ Rust    📅 2026-04-03    👤 surdeus    👁️ 7      

surdeus

Here is the code: I want to take the field a of <() as GetConst>::VALUE, if I put the VALUE into global const then everything is good, but the compiler doesn't recognize it in trait const. I have an idea that to take a while mem::forget the rest, but if so I have to forget all of the rest field by hand. Is there a better way? Thanks.

(I have modified the code, the following is the new version)

#![allow(dead_code)]

struct NotCopy(u64);

enum MaybeDrop {
    NoDrop(NotCopy),
    Drop(String)
}

struct Bundled {
    a: MaybeDrop,
    b: MaybeDrop,
    c: MaybeDrop,
    d: MaybeDrop,
    // ... many more ...
}

const _VALUE: Bundled = Bundled {
    a: MaybeDrop::NoDrop(NotCopy(1234567890)),
    b: MaybeDrop::NoDrop(NotCopy(9876543210)),
    c: MaybeDrop::NoDrop(NotCopy(2342374982234)),
    d: MaybeDrop::NoDrop(NotCopy(393407032974)),
};

trait GetConst {
    const VALUE: Bundled = _VALUE;
}
impl GetConst for () {}

// --------------------------
// Not allowed to edit above code

// ok
const _EXTRACT: MaybeDrop = _VALUE.a;

// error[E0493]: destructor of `Bundled` cannot be evaluated at compile-time
const EXTRACT: MaybeDrop = <() as GetConst>::VALUE.a;

8 posts - 3 participants

Read full topic

🏷️ Rust_feed