Declaring array using a constant expression for its size

三世轮回 提交于 2019-12-01 02:12:45

问题


I have a newtype wrapper around an array. I assumed that I could use size_of instead of manually passing the size of the array around, 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'm using the nightly: 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

The Rust Reference on Array Expressions makes me think that this should work:

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:


Your SIZE definition is not legal; it’s just that the errors in it occur later than the error on the array construction. If you change [0u8, ..SIZE] to [0u8, ..6] just so that that part works, you find the 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 simply can’t call size_of like that at present.

An alternative is to invert things so that SIZE is the canonical definition and the other places 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 obsoleted, and the compiler error messages have been improved so that they are even more clear.

Furthermore, with #42859 recently landed, rustc nightly will allow using size_of in a constant context, provided the crate has #![feature(const_fn)] (and when #43017 lands, that won’t be needed any more either, and then it will filter through to stable).

In other words, improvements to the language have made this no longer an issue.



来源:https://stackoverflow.com/questions/26976104/declaring-array-using-a-constant-expression-for-its-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!