Declaring array using a constant expression for its size
我在数组周围有一个新型包装器。 我以为我可以使用
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.
您的
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>(); ^~~~~~~~~~~~~~~~~~~~~~~~~~~ |
您根本无法像现在这样拨打
另一种方法是反转事物,使
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的着陆,只要板条箱具有
换句话说,对语言的改进使得这不再是一个问题。