在 Rust 的堆上创建一个固定大小的数组 [英] Creating a fixed-size array on heap in Rust

查看:73
本文介绍了在 Rust 的堆上创建一个固定大小的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用以下代码:

fn main() {
    let array = box [1, 2, 3];
}

,在我的程序中,它导致编译错误:error: obsolete syntax: ~[T] is no longer a type.

, in my program, and it results in a compile error: error: obsolete syntax: ~[T] is no longer a type.

AFAIU,Rust 中没有动态大小数组(大小必须在编译时知道).但是,在我的代码片段中,数组确实具有静态大小,并且应该是 ~[T, ..3] 类型(拥有大小为 3 的静态数组),而编译器说它具有类型 ~[T].无法在堆上分配静态大小的数组是否有任何深层原因?

AFAIU, there are no dynamic size arrays in Rust (the size has to be known at compile time). However, in my code snippet the array does have static size and should be of type ~[T, ..3] (owned static array of size 3) whereas the compiler says it has the type ~[T]. Is there any deep reason why it isn't possible to get a static sized array allocated on the heap?

附言是的,我听说过 Vec.

P.S. Yeah, I've heard about Vec.

推荐答案

据我所知,框表达式是实验性的.你可以使用 Box::new() 和下面类似的代码来抑制警告.

As far as I know the box expression is experimental. You can use Box::new() with something like the code below to suppress warnings.

fn main() {
    let array1 = Box::new([1, 2, 3]);
    // or even
    let array2: Box<[i32]> = Box::new([1, 2, 3]);
}

查看下面 Shepmaster 的评论,因为它们是不同的类型.

Check out the comment by Shepmaster below, as these are different types.

这篇关于在 Rust 的堆上创建一个固定大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆