如何创建带类型归属的盒装切片?

时间:2017-07-17 13:42:10

标签: rust

创建一个盒装切片很容易:

fn main() {
    let _ = Box::new([42, 0]);
}

但如果我想添加类型归属:

fn main() {
    let _ = Box::<[i32]>::new([42, 0]);
}

我明白了:

error: no associated item named `new` found for type `std::boxed::Box<[i32]>` in the current scope
  --> src/main.rs:2:13
   |
 2 |     let _ = Box::<[i32]>::new([42, 0]);
   |             ^^^^^^^^^^^^^^^^^
   |
   = note: the method `new` exists but the following trait bounds were not satisfied: `[i32] : std::marker::Sized`

这真的很奇怪,因为这有效:

fn main() {
    let _: Box<[i32]> = Box::new([42, 0]);
}

2 个答案:

答案 0 :(得分:4)

  

创建盒装切片很容易

除非你没有这样做。如果您print the type,您可以看到Box::new([1, 2])创建盒装数组,而不是切片。另一方面,let _: Box<[i32]> = Box::new([1, 2])创建一个盒装数组并将其转换为盒装切片。这些有不同的类型。值得注意的是,第一种类型在编译时具有已知长度,第二种类型不再具有长度。

您也可以使用as

fn main() {
    let _ = Box::new([1, 2]) as Box<[i32]>;
}

Box::<[i32]>::new([1, 2])由于错误消息显示的原因而无法正常工作:T不是SizedT直接映射到要装箱的类型。

Box::new([1, 2]) as Box<[i32]>有效,因为已将大小的项目传递给Box::new,然后使用unsized coercions将其转换为带有未校对内部位的类型。

看来,未经授权的强制行为不适用于actual type ascription,这是每晚Rust中不稳定的特征:

#![feature(type_ascription)]

fn main() {
    let foo = Box::new([1, 2]): Box<[i32]>;
}

对于此特定的情况,您可以使用into_boxed_slice,这样可以避免任何堆栈分配。

vec![1, 2].into_boxed_slice();

答案 1 :(得分:2)

这是experimental feature

#![feature(type_ascription)]

fn main() {
    let _ = Box::new([42, 0]: [i32; 2]);
}

此外,在这种情况下,您需要明确长度。

相关问题