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

2023-11-26

我有一个围绕数组的新类型包装器。我以为我可以使用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));
}

(婴儿围栏链接)

我正在使用每晚: 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

The 数组表达式的 Rust 参考让我认为这应该有效:

In the [expr ',' ".." expr]形式,后面的表达式".."必须是可以在编译时计算的常量表达式,例如文字或静态项。


Your SIZE定义不合法;只是其中的错误发生得晚于数组构造上的错误。如果你改变[0u8, ..SIZE] to [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));
}

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

此外,与#42859最近登陆,rustc nightly 将允许使用size_of在恒定的环境中,只要板条箱有#![feature(const_fn)](什么时候#43017土地,也不再需要,然后它会过滤到稳定)。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用常量表达式声明数组的大小 的相关文章

随机推荐