Raylib: Cannot borrow `rl` as immutable because it is also borrowed as mutable

Hello!

I'm new using Rust and it's my first compiled language I'm learning.

I'm stuck with the following code:

extern crate raylib;

use raylib::prelude::*;
use raylib::consts::KeyboardKey::*;

struct Position {
    x: i32,
    y: i32
}

fn main() {
    let (mut rl, thread) = raylib::init()
        .size(1280, 720)
        .title("Hello, World")
        .build();

    rl.set_target_fps(60);

    let text_position = Position { x: 12, y: 12 };

    while !rl.window_should_close() {
        let mut d = rl.begin_drawing(&thread);

        if rl.is_key_down(KEY_A) {
            d.draw_text("Hello, world!!!", text_position.x, text_position.y, 20, Color::BLACK);
        }

        d.clear_background(Color::WHITE);
        d.draw_text("Hello, world!", text_position.x, text_position.y, 20, Color::BLACK);
    }
}

with the error:

cannot borrow `rl` as immutable because it is also borrowed as mutable

It referred to the line "if rl.is_key_down(KEY_A) {}".

Could you please explain me what I'm doing wrong? :blush:

Thank you very much for the help!

Welcome!

begin_drawing takes an exclusive borrow (&mut self) of the RaylibHandle rl. This acts like a lock, preventing anything else from accessing rl while d is still in use.

You could fix this by accessing rl before the `begin_drawing call:

let say_hello = rl.is_key_down(KEY_A);
let mut d = rl.begin_drawing(&thread);
if say_hello {
    d.draw_text("Hello, world!!!", text_position.x, text_position.y, 20, Color::BLACK);
}

Or by calling d.is_key_down instead, since RaylibDrawHandle also provides access to all the RaylibHandle methods:

let mut d = rl.begin_drawing(&thread);
if d.is_key_down(KEY_A) {
    d.draw_text("Hello, world!!!", text_position.x, text_position.y, 20, Color::BLACK);
}
1 Like

Thank you a lot for the explanation and the welcome message :slightly_smiling_face: