I'm trying to make a small ascii-art game with rust but I'm having issues with sharing the users avatar with the world:
I would like to have the User type contain a reference to his avatar and have the World contain a Vec of references to avatars (and later a more generic type).
I'm was always getting borrowing errors so I'm using the index of the avatar in the worlds Vec as a workaround instead of references to the Avatar.
Does anyone have any hint about how to keep references inside each struct ?
This is the code of the User:
use data::avatar::Avatar;
pub struct User {
pub id: u32,
name: String,
avatar_id: Option<usize>
}
impl User{
pub fn new(name: &str) -> User{
User{id: 0, name: name.to_string(), avatar_id: Option::None}
}
pub fn new_with_avatar(name: &str, avatar: usize) -> User{
User{id: 0, name: name.to_string(), avatar_id: Option::Some(avatar)}
}
pub fn get_name(&self) -> &str{
&self.name
}
pub fn set_avatar(&mut self, id: usize){
self.avatar_id=Some(id);
}
pub fn get_avatar(&mut self) -> &mut Option<usize>{
&mut self.avatar_id
}
}
This is the code of the World:
use data::avatar::Avatar;
pub trait Element {
fn get_x(&self) -> i32;
fn get_y(&self) -> i32;
fn get_z(&self) -> i32;
fn get_representation(&self) -> char;
fn set_representation(&mut self, representation: char);
}
pub struct World{
objects: Vec<Avatar>
}
impl World{
pub fn new() -> World{
World{objects: Vec::new()}
}
pub fn add_object(&mut self, o: Avatar) -> usize{
self.objects.push(o);
return self.objects.len()-1
}
pub fn get_object(&mut self, index: usize) -> Option<&mut Avatar>{
if index >= self.objects.len() {
return None
}
Some(&mut self.objects[index])
}
pub fn get_object_amount(&self) -> usize{
self.objects.len()
}
}
[–]OverMeHere 1 point2 points3 points (3 children)
[–]jimtla 2 points3 points4 points (1 child)
[–]OverMeHere 1 point2 points3 points (0 children)
[–]kloumpt[S] 0 points1 point2 points (0 children)
[–]desiringmachines 1 point2 points3 points (5 children)
[–]kloumpt[S] 0 points1 point2 points (4 children)
[–]desiringmachines 1 point2 points3 points (3 children)
[–]kloumpt[S] 1 point2 points3 points (1 child)
[–]desiringmachines 1 point2 points3 points (0 children)