1

When there are multiple constant variables in a rust program, and they get initialized (on compile time) by a constant function, in which order are they initialized? How can I assure safety if the initialization of one depends on the other? For example:

const FIRST : i32 = first_fun();
const SECOND : i32 = second_fun();

const fn first_fun() -> i32 {
    10
}

const fn second_fun() -> i32 {
    FIRST * 2
}

How can I guarantee correct initialization? Of course second_fun() could call first_fun(), but if first_fun() is computationally heavy that seems like unnecessary overhead, especially if one of the constants is an array.

Svetlin Zarev
  • 14,713
  • 4
  • 53
  • 82
Fowlron
  • 99
  • 1
  • 11
  • Maybe https://doc.rust-lang.org/std/sync/struct.Once.html helps? – orlp Aug 29 '21 at 16:57
  • 3
    There is only one “correct initialization”, so I’m not sure what you’re concerned about here? As for unnecessary overhead, the compiler will evaluate the const fn once and cache that result. – eggyal Aug 29 '21 at 17:00
  • @eggyal So that implies the compiler will intelligently initialize them in the correct order? This wasn't clear to me from the documentation I read but if that's the case that would solve the problem, yes – Fowlron Aug 29 '21 at 17:03
  • 2
    What other order is there? `SECOND` cannot be resolved without first resolving `FIRST`. It’s simply not possible. – eggyal Aug 29 '21 at 17:09
  • Unless you do a circular relation there is no problem, A naive but straight forward implementation would evaluate one, then evaluate two and reevaluate one. – Stargateur Aug 29 '21 at 17:37

0 Answers0