This `if` expression has a condition, but no block

Hello, i have this snippet:

if keyboard::is_key_pressed(ctx, keyboard::KeyCode::Numpad0) {            
            
            
            for unit in &mut self.vecsquad[0] {unit.selected = true;}
            wait_500ms();

            for unit in &mut self.vecsquad[0] {println!(" Unit---->   {:?} ", unit);}


            for unit in &mut self.vecunit {
                if unit in self.vecsquad[0] {unit.selected = true;}
            }
            wait_500ms();            
        }

and the error:
if unit in self.vecsquad[0] {unit.selected = true;}
** | -- ^^ expected {**
** | |**
** | this if expression has a condition, but no block**

in is only a keyword in the for ... in Iterator { ... } construct. Try something like

if self.vecsquad[0].contains(&unit) { ... }

(Without knowing the full datatypes, I can’t be sure of the exact call you’ll need)

5 Likes

units are struct owned inside the field vecunit inside the main struct MainState.

Struct Unit {
    squad: Option<usize>
}

Struct MainState {
    vecunit: Vec<Unit>,
    vecunitSelected: Vec<Unit>,
    vecsquad: Vec<Vec<Unit>>,
}

impl EventHandler for MainState {
    fn update(&mut self, ctx: &mut ggez::Context) -> ggez::GameResult {   
        if keyboard::is_key_pressed(ctx, keyboard::KeyCode::Key0) {
            println!(" {:?} ", self.vecsquad);
            for unit in &mut self.vecunitSelected {unit.squad = Some(0); self.vecsquad[0].push(*unit);}
            wait_500ms();
            

            println!(" {:?} ", self.vecsquad);
        }
            for unit in &mut self.vecunit { 
        	    unit.check_progression_current_task();
        	    unit.update_rect_pos();
        }
            if self.vecsquad[0].contains(&unit) { unit.selected = true; }
            wait_500ms();

cannot find value unit in this scope
** --> src/main.rs:795:43**
** |**
795 | if self.vecsquad[0].contains(&unit) { unit.selected = true; }
** | ^^^^ not found in this scope**

Reformat the code, it will make sense immediately.
If you use a proper editor like VSCode or CLion, it can do that automatically.
If you work with an editor with no rust support, you may invoke rustfmt directly.

You can also use Rust playground - it has rustfmt installed (under Tools menu on the top right). Here's your code with some syntax fixes after formatting.

Do use "cargo fmt" on your code. It will make it much clearer for yourself and others to see what is going on.

As far as I can tell anything called "unit" in that snippet only exists within the scope of a "for unit... " loop.

As such it does not exist in the code following the loop.

thank you everybody cargo fmt is very good !
also usefull inside rust play

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.