arrays - 使用常量表达式声明数组的大小

标签 arrays rust rust-obsolete

我有一个数组的新类型包装器。我假设我可以使用 size_of 而不是手动传递数组的大小,但编译器认为我错了。

use std::mem::{size_of, size_of_val};

#[repr(C, packed)]
struct BluetoothAddress([u8, ..6]);

fn main() {
    const SIZE: uint = size_of::<BluetoothAddress>();

    let bytes = [0u8, ..SIZE];
    println!("{} bytes", size_of_val(&bytes));
}

( playpen link )

我每晚使用:rustc 0.13.0-nightly (7e43f419c 2014-11-15 13:22:24 +0000)

此代码因以下错误而失败:

broken.rs:9:25: 9:29 error: expected constant integer for repeat count, found variable
broken.rs:9     let bytes = [0u8, ..SIZE];
                                    ^~~~
error: aborting due to previous error

Rust Reference on Array Expressions让我觉得这应该可行:

In the [expr ',' ".." expr] form, the expression after the ".." must be a constant expression that can be evaluated at compile time, such as a literal or a static item.

最佳答案

您的SIZE 定义不合法;只是其中的错误发生的时间晚于数组构造上的错误。如果您将 [0u8, ..SIZE] 更改为 [0u8, ..6] 以便该部分正常工作,您会发现 SIZE< 存在问题声明:

<anon>:7:24: 7:53 error: function calls in constants are limited to struct and enum constructors [E0015]
<anon>:7     const SIZE: uint = size_of::<BluetoothAddress>();
                                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<anon>:7:24: 7:51 error: paths in constants may only refer to items without type parameters [E0013]
<anon>:7     const SIZE: uint = size_of::<BluetoothAddress>();
                                ^~~~~~~~~~~~~~~~~~~~~~~~~~~

目前你根本不能像那样调用 size_of

另一种方法是反转事物,使 SIZE 成为规范定义,其他地方使用它:

use std::mem::{size_of, size_of_val};

const SIZE: uint = 6;

#[repr(C, packed)]
struct BluetoothAddress([u8, ..SIZE]);

fn main() {
    let bytes = [0u8, ..SIZE];
    println!("{} bytes", size_of_val(&bytes));
}

更新:在 Rust 1.0 中,这个问题实际上已被废弃,并且编译器错误消息已得到改进,因此它们更加清晰。

此外,使用 #42859最近着陆,rustc nightly 将允许在常量上下文中使用 size_of,前提是箱子有 #![feature(const_fn)](当 #43017 着陆时,它赢了也不再需要,然后它将过滤到稳定版)。

换句话说,语言的改进使这不再是一个问题。

关于arrays - 使用常量表达式声明数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26976104/

相关文章:

java初学者: print two dimensional array element in a String

arrays - 为什么 pipe equals 不适用于 Ruby 中的 tap?

rust - 如何创建一个全局的、可变的单例?

rust - 可以吗?是否为Option和Result以外的类型定义了运算符?

string - 我如何在 Rust 中将 &str 转换为 ~str?

php - 从 MySQL 结果创建数组,并添加新项目

c - C中对象的函数指针

rust - 有没有一种内存有效的方法来更改固有实现的行为?

rust - &T 和 T/&, ~T 和 T/~ 的区别

rust - Rust 中的 "0is"表示法是什么?