Declaring an array using a constant expression for its size

I have a newtype wrapper around an array. I suggested that I could use size_of instead of manually passing the size of the array, but the compiler thinks I'm wrong.

 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 )

I am using a night clock: rustc 0.13.0-nightly (7e43f419c 2014-11-15 13:22:24 +0000)

This code fails with the following error:

 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 makes me think this should work:

In the form [expr ',' ".." expr] expression after ".." must be a constant expression that can be evaluated at compile time, for example, by a literal or a static element.

+7
arrays rust rust-obsolete
source share
1 answer

Your definition of SIZE not legal; its simple that errors in it occur later than errors in the array design. If you change [0u8, ..SIZE] to [0u8, ..6] only so that this part works, you will find problems with the SIZE declaration:

 <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>(); ^~~~~~~~~~~~~~~~~~~~~~~~~~~ 

You just can't call size_of like this at the moment.

An alternative is to invert things, so SIZE is a canonical definition, while others use it:

 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: With Rust 1.0, this question has been effectively deprecated, and compiler error messages have been improved so that they are even more understandable.

Also, with # 42859 recently landed, rustc nightly will allow you to use size_of in a constant context if the box has #![feature(const_fn)] (and when # 43017 lands that are no longer needed, and then it is filtered to stable).

In other words, improvements in the language made this no longer a problem.

+6
source share

All Articles