【问题标题】:Why doesn't vec![[EMPTY; SIZEY]; SIZEX] produce the type Vec<[[i32; SIZEY]; SIZEX]>?为什么没有 vec![[EMPTY;尺寸]; SIZEX] 产生类型 Vec<[[i32;尺寸];尺寸]>?
【发布时间】:2021-09-28 02:42:54
【问题描述】:

这个程序很好:

const EMPTY: i32 = 0;
const SIZEX: usize = 4;
const SIZEY: usize = 4;

fn main() {
    let mut test = vec![[EMPTY; SIZEY]; SIZEX];
    test[2][3] = 4;
    // test.what();
    println!("Hello, world:{}", test[2][3]);
}

当我取消注释 test.what() 行以查看 test 的类型时,编译器会发出错误:

error[E0599]: no method named `what` found for struct `Vec<[i32; 4]>` in the current scope
 --> src/main.rs:8:10
  |
8 |     test.what();
  |          ^^^^ method not found in `Vec<[i32; 4]>`

我期待test 的类型类似于Vec&lt;[[i32; SIZEY]; SIZEX]&gt;。我错过了什么?

【问题讨论】:

标签: rust


【解决方案1】:

vec![t; N] 宏将生成长度为NVec&lt;T&gt;(其中Tt 的类型)。长度不是类型的一部分,因为它是动态的。

【讨论】:

  • 谢谢。我忽略了长度不在类型中的事实,只要您记得 Vec 是动态数组,这一点就很明显了。我明确不想要一个数组,因为我正在寻找堆分配(非常大)的数组。而且我还测试了使用 vec.into_boxed_slice() 创建盒子数组的“盒子”技巧
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-30
相关资源
最近更新 更多