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

标签 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 中的消息更友好,并确认该功能尚未实现。引用同箱常量是 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

最佳答案

错误信息:

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 的 future 版本中。

关于rust - 如何用其他常量初始化顶级常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9942426/

相关文章:

rust - 从 NaiveDateTime 转换为 DateTime<Local>

rust - 你将如何在 Rust 中实现双向链表?

rust - 如何在Rust中组合if-let语句?

rust - 为什么我无法使用 Tokio UnixStream 与 fork 子进程通信?

sockets - 循环中匹配臂中的变量来自哪里?

rust - 通过共享框 ptr 访问时如何使我的结构字段可变?

使用rust "error: moving out of immutable field"

unit-testing - 在单元测试中评估多个断言 - 不要在第一个失败的断言处停止

rust - Rust 泛型中的常量值

Rust 中的套接字