Defining a const variable with sqrt



How do I pass the sqrt of a value to a const variable?

The following sample code throws an error

    const A: f64 = 1.0/4.0_f64.sqrt();

    fn main() {

       println!("{}", A);
error[E0015]: calls in constants are limited to tuple structs and tuple variants
 --> src\
3 | const A: f64 = 1.0/4.0_f64.sqrt();
  |                    ^^^^^^^^^^^^^^
note: a limited form of compile-time function evaluation is available on a nightly compiler via `const fn`
 --> src\


I don’t think const fn are powerful enough to do sqrt right now.

Looking at the sqrt implementation, it has an if statement, which is currently unsupported on const fn.


Your example is obviously trivial, but if you can express your number in terms of sqrt(2) or sqrt(π), you may be able to build it with the standard consts:


The following constants are required globally in my code:
const A: f64 = 1.0/(2.0_f64.sqrt());
const B: f64 = 1.0/10.0_f64.sqrt();
const C: f64 = 1.0/42.0_f64.sqrt();

Rust should support this by default. It is not efficient to hard code the sqrt of a number before it can be assigned to a const variable.


I don’t think anyone will argue otherwise… but it doesn’t, so you don’t really have any choice but to hard-code those values.


You could use lazy_static as a workaround in the mean-time.


I have submitted a Change Request to the language design team. Hopefully, they will be introduce this feature very soon.


Thanks for the workaround. I believe this should also work on an embedded target platform (e.g RaspberryPI+ B), right?

extern crate lazy_static;

lazy_static! {
    static ref A: f64 = 1.0/(2.0_f64.sqrt());
    static ref B: f64 = 1.0/10.0_f64.sqrt();
    static ref C: f64 = 1.0/42.0_f64.sqrt();


fn main() {
   println!("A = {} \nB = {}\nC = {}", *A, *B, *C);
PS C:\Users\eshikafe\Documents\GitHub\ar-lte\rs_src> cargo run
   Compiling lazy_static v1.2.0
   Compiling ar_lte_lib_rust v0.1.0 (C:\Users\eshikafe\Documents\GitHub\ar-lte\rs_src)
    Finished dev [unoptimized + debuginfo] target(s) in 1.17s
     Running `target\debug\ar_lte_lib_rust.exe`
A = 0.7071067811865475
B = 0.31622776601683794
C = 0.1543033499620919
PS C:\Users\eshikafe\Documents\GitHub\ar-lte\rs_src>