Feature Request: destructuring declarations for `const`

Currently, we have destructing declarations for let, and we can apply mut to each individual variable binding. Destructuring assignment is also being worked on too.

Yet, I've seen nothing for const declarations, and the situation with const is arguable worse, as constants can be initialized at the global scope, forcing code authors to workaround this by either leave unnecessary temporary globals around, e.g.:

const TEMPORARY_TUPLE: (u8, u8) = func(10);
const X: u8 = TEMPORARY_TUPLE.0;
const Y: u8 = TEMPORARY_TUPLE.1;

duplicating expressions:

const X: u8 = func(10).0;
const Y: u8 = func(10).1;

or possibly creating arbitrary modules to create scopes:

mod temporaries {
  const TEMPORARY_TUPLE: (u8, u8) = func(10);
  pub const X: u8 = TEMPORARY_TUPLE.0;
  pub const Y: u8 = TEMPORARY_TUPLE.1;
}

use temporaries::{X, Y};

or maybe even other workarounds.

Has this suggestion be raised anywhere yet?

If not, I'd like to presume that this would be an objectively beneficial feature for the language. If anyone has any arguments against the introduction of this, or if it is infeasible to implement for any reason(s), I'd like to hear your feedback :slight_smile:

11 Likes

That makes sense to me, code like this works:

let (x, y): (u8, u16) = (1, 2);

So I could see something like this working eventually:

const (X, Y): (u8, u16) = (1, 2);
5 Likes

I'm no expert on const, but how would this interact with dropping? If the destructuring pattern drops a subset of values (const (_, x) = (MyStruct, MyStruct)), do they need to be trivially droppable?

Why would it be any different than doing const _ = MyStruct for the first item?

3 Likes

Had no idea that was possible, maybe it's a non-issue

EDIT: permit `Drop` types in constants (tracking issue for RFC #1440) · Issue #33156 · rust-lang/rust · GitHub

Yup, I agree. I wouldn't expect any new semantics to be introduced here, so I'd defer to that example too.

@joelgallant I don't believe it's possible to drop a value in a const context anyways? If not, I believe that this would indeed be a non-issue.

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