Advertisement
Guest User

Untitled

a guest
Mar 24th, 2023
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.44 KB | None | 0 0
  1. #![allow(unused_variables, dead_code)]
  2.  
  3. use std::fmt::Display;
  4.  
  5. const EMPTY_CHAR: &str = " ";
  6.  
  7. struct Point {
  8.     x: usize,
  9.     y: usize,
  10. }
  11.  
  12. struct Character {
  13.     position: Point,
  14.     symbol: String,
  15. }
  16.  
  17. struct Game<'a> {
  18.    arena: Vec<Vec<&'a str>>,
  19.     characters: Vec<Character>,
  20. }
  21.  
  22. impl Game<'_> {
  23.    fn new(size: (usize, usize)) -> Game<'static> {
  24.         Game {
  25.             arena: vec![vec![EMPTY_CHAR; size.0]; size.1],
  26.             characters: vec![],
  27.         }
  28.     }
  29.  
  30.     fn add_character(&mut self, character: Character) {
  31.         let position = &character.position;
  32.         //   ERROR HERE               character.symbol does not live enough
  33.         self.arena[position.x][position.y] = &character.symbol;
  34.         //  ERROR HERE      cannot move out of character because it is borrowed
  35.         //                  move out of character occurs here
  36.         self.characters.push(character);
  37.     }
  38. }
  39.  
  40. impl Display for Game<'static> {
  41.    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  42.         for line in &self.arena {
  43.             for cell in line {
  44.                 print!("{}", cell);
  45.             }
  46.             println!();
  47.         }
  48.  
  49.         std::fmt::Result::Ok(())
  50.     }
  51. }
  52.  
  53. fn main() {
  54.     let mut game = Game::new((20, 10));
  55.  
  56.     let prince = Character {
  57.         position: Point { x: 3, y: 4 },
  58.         symbol: String::from("P"),
  59.     };
  60.  
  61.     game.add_character(prince);
  62.  
  63.     println!("{}", game);
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement