关于rust:使用常量表达式声明数组的大小

Declaring array using a constant expression for its size

我在数组周围有一个新型包装器。 我以为我可以使用size_of来代替手动传递数组的大小,但是编译器认为我错了。

1
2
3
4
5
6
7
8
9
10
11
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));
}

(游戏围栏链接)

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

此代码失败,并出现以下错误:

1
2
3
4
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参考使我认为这应该可行:

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声明存在的问题:

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

您根本无法像现在这样拨打size_of

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

1
2
3
4
5
6
7
8
9
10
11
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的着陆,只要板条箱具有#![feature(const_fn)](并且当#43017着陆时,也不再需要它,则rustc每晚将允许在恒定上下文中使用size_of,然后它将进行过滤) 到稳定)。

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