如何用其他常量初始化顶级常量?

时间:2012-03-30 11:54:20

标签: rust rust-obsolete

我想使用float::consts::pi初始化一些顶级常量。例如:

import float::consts::pi;

const pi2:float = pi*pi;

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

我收到这些错误:

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;
                             ^~

如果我写的话,编译成功:

const pi2:float = 3.14*3.14;

但如果我定义自己的pi

,则不然
const pi:float = 3.141592653589793;
const pi2:float = pi*pi;

我正在使用rust-0.2。

更新即可。 rust-0.3.1中的消息更友好,并确认该功能尚未实现。引用相同的crate常量是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

2 个答案:

答案 0 :(得分:4)

错误消息:

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;
                             ^~

表示在Rust 0.2编译器中当前没有针对这些情况的实现。 Rust无法解析标识符pi的值。

所需的功能可能会出现在Rust的未来版本中。

答案 1 :(得分:0)

我无法验证,因为我目前无法在我的机器上编译Rust,但我认为您的问题可能是pi常量被定义为类型c_float而不是类型{ {1}}。尝试:

float

看看是否有任何影响。如果还需要导入类型,您可能还需要导入行const pi2: c_float = pi*pi;