我有一个数组的新类型包装器。我假设我可以使用 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/