[英]Instantiating a 2d Vec in a Struct?
使用構造函數返回新的struct對象時,無法實例化vec。 我嘗試過的語法(可能使用了不正確的collect())吐出了大量的編譯器錯誤。
fn main() {
let level = Level::new();
}
struct Level {
tiles: Vec<Vec<Tile>>
}
struct Tile {
idx: i32
}
impl Level {
fn new() -> Level {
Level {
tiles: {
let mut t = Vec::new();
let mut t2 = Vec::new();
for x in range(0, 80) {
for y in range(0, 24) {
t2.push(Tile::new(x, y));
}
t.push(t2);
}
t
}
}
}
impl Tile {
fn new(x: i32, y: i32) -> Tile {
Tile { pos: Point { x: x, y: y } }
}
}
struct Point {
x: i32,
y: i32
}
我得到這些錯誤:
src/game/dungeon/level/mod.rs:47:25: 47:27 error: use of moved value: `t2`
src/game/dungeon/level/mod.rs:47 t2.push(Tile::new(x, y));
^~
src/game/dungeon/level/mod.rs:49:28: 49:30 note: `t2` moved here because it has type `collections::vec::Vec<game::dungeon::level::Tile>`, which is non-copyable
src/game/dungeon/level/mod.rs:49 t.push(t2);
^~
src/game/dungeon/level/mod.rs:49:28: 49:30 error: use of moved value: `t2`
src/game/dungeon/level/mod.rs:49 t.push(t2);
^~
src/game/dungeon/level/mod.rs:49:28: 49:30 note: `t2` moved here because it has type `collections::vec::Vec<game::dungeon::level::Tile>`, which is non-copyable
src/game/dungeon/level/mod.rs:49 t.push(t2);
^~
是的,您做錯了。 在C / C ++,BTW中,類似的代碼也將不正確。
let mut t = Vec::new();
let mut t2 = Vec::new();
for x in range(0, 80) {
for y in range(0, 24) {
t2.push(Tile::new());
}
t.push(t2);
}
問題是,您總是在內部循環中將相同的t2
推入,然后始終將相同的t2
推入t
。 后者違反了所有權語義,因此Rust編譯器正確地告訴您有關使用移動值的信息。
慣用的方法是使用迭代器,它看起來可能像這樣:
(0..80).map(|_| (0..24).map(|_| Tile::new()).collect()).collect()
如果您需要訪問索引,則可以使用map()
閉包參數:
(0..80).map(|x| (0..24).map(|y| Tile::new(x, y)).collect()).collect()
編譯器應自動推斷出所需的collect()
結果類型。
弗拉基米爾的回答確實不錯,但是我感覺功能樣式可能會在這里隱藏錯誤。
您實際上離解決方案不遠。 問題是,您不能在外循環的每次迭代中重復使用相同的t2
。 因此,最簡單的轉換是在外部循環內創建t2
:
impl Level {
fn new() -> Level {
Level {
tiles: {
let mut t = Vec::new();
for x in range(0, 80) {
let mut t2 = Vec::new(); // Moved!
for y in range(0, 24) {
t2.push(Tile::new(x, y));
}
t.push(t2);
}
t
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.