Is there a better way to get anonymous functions in constants than `loop {}`?

Currently, I am working on a project where I use const (As in const x: i32 = 0;), where the value has to be computed. The reason I'm using const is because it needs to be in the global scope, and I do not want to use static, as that would force me to use unsafe way too many times (So why would I use Rust at that point?).

I am using

const x: i32 = loop {
    break y + z;

for this purpose. I know this is very unclear, and the compiler probably has no idea how to optimize this garbage code.

Is there a closure-like way to compute a value for a const value, or will I be stuck with loop { break x; }?

That's true for a static mut, which you should avoid, but not for a plain ol' static.

I don't get the point of your loop either.

// `static` works too
const Y: i32 = 0;
const Z: i32 = 0;
const X: i32 = Y + Z;

// Doesn't work (non-constant value)
fn foo(y: i32, z: i32) {
    const x: i32 = y + z;

// Doesn't work (non-constant value)
fn bar(y: i32, z: i32) {
    const x: i32 = loop { break y + z; };
1 Like

if you just want curly braces for style, you can just use curly braces, without loop:

const x: i32 = {
    y + z
1 Like

You can also use break without loop:

const X: i32 = 'result: {
    break 'result Y + Z;

But still it's not clear why the original code is ever needed. You can usually (always?) just assign result directly.


My best inference is perhaps they have a complex formula with many intermediate variables that they want scoped just to the initialization of this constant.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.