Search code examples
rustrust-obsolete

How to initialize top-level constants with other constants?


I'd like to initialize some top-level constants using float::consts::pi. For example:

import float::consts::pi;

const pi2:float = pi*pi;

fn main() {
    io::println(#fmt("pi^2=%.4f", pi2));
}

I get these errors:

pi2.rs:3:18: 3:20 error: constant contains unimplemented expression type
pi2.rs:3 const pi2:float = pi*pi;
                           ^~
pi2.rs:3:21: 3:23 error: constant contains unimplemented expression type
pi2.rs:3 const pi2:float = pi*pi;
                             ^~

Compilation is successful if I write:

const pi2:float = 3.14*3.14;

But it is not if I define my own pi:

const pi:float = 3.141592653589793;
const pi2:float = pi*pi;

I'm using rust-0.2.

Update. Messages in rust-0.3.1 are friendlier, and confirm that the feature is not implemented yet. Referencing same-crate constants is now allowed:

$ rustc pi2.rs
pi2.rs:2:18: 2:20 error: paths in constants may only refer to crate-local constants
pi2.rs:2 const pi2:float = pi*pi;
                           ^~
pi2.rs:2:21: 2:23 error: paths in constants may only refer to crate-local constants
pi2.rs:2 const pi2:float = pi*pi;
                              ^~
error: internal compiler error: unexpected failure
note: the compiler hit an unexpected failure path. this is a bug
note: try running with RUST_LOG=rustc=0,::rt::backtrace to get further details and report the results to github.com/mozilla/rust/issues

Solution

  • The error messages:

    pi2.rs:3:18: 3:20 error: constant contains unimplemented expression type
    pi2.rs:3 const pi2:float = pi*pi;
                               ^~
    pi2.rs:3:21: 3:23 error: constant contains unimplemented expression type
    pi2.rs:3 const pi2:float = pi*pi;
                                 ^~
    

    mean that there is currently no implementation for these cases in the Rust 0.2 compiler. Rust is unable to resolve the value of the identifier pi.

    The required functionality may appear in a future release of Rust.