- Background:
I want to create an app using Tauri. It allows you to create app with html/JS frontend and Rust backend.
For communicating between frontend and backend, you can create tauri-commands using #[tauri::command]
macro. This allows you to create functions that can be called in the frontend.
I was trying to implement the game-of-life in rust and display it using tauri.
- Game Implementation Overview:
I have declared the game struct
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cell {
Dead = 0,
Alive = 1,
}
pub struct Universe {
width: u32,
height: u32,
cells: Vec<Cell>,
}
There are three functions that are important:
impl Universe {
pub fn new() -> Universe // for creating the Game object
pub fn render(&self) -> String // for getting the game state as string, so that it can be rendered on the fronend.
pub fn tick(&mut self) // For changing the cell to the next state
}
- Problems I am facing
I want to create two tauri-commands
#[tauri::command]
fn get_game_state() -> String
#[tauri::command]
fn tick_game()
The problem is that I cannot pass the game object to these functions as a parameter. So I thought of creating a global game object. Rust was giving error with this, so I used an external crate: lazy_static
to initialize the global game object.
lazy_static! {
static ref GAME: Universe = {
let mut game = Universe::new();
game
};
}
Now I'm implementing the tauri-commands as follows:
#[tauri::command]
fn get_game_state() -> String {
GAME.render()
}
#[tauri::command]
fn tick_game() {
GAME.tick();
}
However, the rust compiler is giving the following error:
error[E0596]: cannot borrow data in dereference of
GAMEas mutable
30 | GAME.tick();
| ^^^^^^^^^^^ cannot borrow as mutable
How do I fix this error ?. Also, is there a better way to manage my game state instead of using global variable. ?