我試圖將新初始化的二維字符陣列傳遞給結構;它說型別不匹配,我不知道如何正確執行;
代碼和錯誤訊息的螢屏截圖
struct Entity<'a> {
dimensions: Vec2,
sprite: &'a mut[&'a mut [char]]
}
impl Entity {
fn new<'a>() -> Self {
let mut sp = [[' '; 3]; 4];
for y in 0..sp.len() {
for x in 0..sp[y].len() {
sp[y][x] = '$';
}
}
return Entity{dimensions: Vec2::xy(3, 4), sprite: &mut sp }
}
}
uj5u.com熱心網友回復:
我認為有幾件事正在發生。
1.)&'a mut[&'a mut [char]]參考一個包含可變字符切片的可變切片。您正在構建的是一個固定的字符陣列矩陣,然后嘗試回傳對其的可變參考。這些不是可互換的型別。
2.) 您正在嘗試回傳對在 中創建的資料的參考new,由于區域變數的生命周期,這不會像那樣作業。
您可能想要的另一種選擇是將結構定義為包含固定大小的陣列矩陣。像這樣:
struct Entity {
sprite: [[char; 3]; 4]
}
impl Entity {
fn new() -> Self {
let mut sp = [[' '; 3]; 4];
for y in 0..sp.len() {
for x in 0..sp[y].len() {
sp[y][x] = '$';
}
}
return Entity{sprite: sp }
}
}
或者你甚至可以為不同的大小使用 const 泛型:
struct Entity<const W: usize, const H: usize> {
sprite: [[char; W]; H]
}
impl<const W: usize, const H: usize> Entity<W, H> {
fn new() -> Self {
let mut sp = [[' '; W]; H];
for y in 0..sp.len() {
for x in 0..sp[y].len() {
sp[y][x] = '$';
}
}
return Entity{sprite: sp }
}
}
如果在編譯時無法知道 sprite 的大小,則需要使用動態大小的資料結構來定義它,例如Vec. 即,Vec<Vec<char>>.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/461077.html
上一篇:如何根據范圍內的兩列回傳最大值
