如何参考2D数组?
我试图将新初始化的2D字符阵列传递给结构;它说类型不匹配,我不知道该如何正确地做。
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 }
}
}
Im trying to pass newly initialized 2d array of chars to the struct; It says that types do not match and I dont know how to do it properly;
Screenshot of code and error message
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 }
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为有几件事正在发生。
1.)
&amp;'a mut [&amp;'a mut [char]]
参考了一个可变切片,其中包含chars的突变切片。您正在构造的是固定的炭矩阵,然后试图返回可变的引用。这些不是可互换的类型。2.)您正在尝试返回
new
中创建的数据的引用,由于本地变量的寿命,这将无法正常工作。一种替代方案,您可能想要的是定义结构以包含固定尺寸的数组矩阵。像这样:
如果您在编译时不知道精灵的大小,则需要使用动态尺寸的数据结构来定义它,例如
; } } return Entity{sprite: sp } } }vec 。即,
vec&lt; vec&lt; char&gt;&gt;
。或者您甚至可以将const grenics用于不同尺寸:
如果您在编译时不知道精灵的大小,则需要使用动态尺寸的数据结构来定义它,例如
vec 。即,
vec&lt; vec&lt; char&gt;&gt;
。I think theres a couple things going on.
1.)
&'a mut[&'a mut [char]]
references a mutable slice containing mutables slices of chars. What you are constructing is a fixed array matrix of chars and then attempting to return mutable references to that. These are not interchangeable types.2.) You are attempting to return references to data created within
new
, which is not going to work like that due to the lifetime of the local variables.An alternative, which might be what you want is to define your struct to contain a fixed size array matrix. Like so:
If you cannot know the size of the sprite at time of compilation, you will need to define it using a dynamically sized data structure, such as a
; } } return Entity{sprite: sp } } }Vec
. Ie.,Vec<Vec<char>>
.Or you could even use const generics for different sizes:
If you cannot know the size of the sprite at time of compilation, you will need to define it using a dynamically sized data structure, such as a
Vec
. Ie.,Vec<Vec<char>>
.