Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected type `bool`, found type `&bool`

Tags:

boolean

rust

I would like to take a bool from a Vec<bool> and compare it in an if statement. How do I solve the following error?

  |
7 |             if cell {
  |                ^^^^ expected bool, found &bool
  |
  = note: expected type `bool`
             found type `&bool`

if cell.clone() works for me but seems a bit hackisch.

like image 597
JaM Avatar asked Jul 31 '26 18:07

JaM


1 Answers

take a bool from a Vec<bool>

Just do that:

let foo = vec![true];
if foo[0] { /* ... */ }

bool implements Copy, so indexing the array will copy the value out.

If you had a reference to the boolean inside the vector, you will need to dereference it:

let foo = vec![true];
if let Some(val) = foo.last() {
    if *val { /* ... */ }
}

Or

let foo = vec![true];
if let Some(&val) = foo.last() {
    if val { /* ... */ }
}
like image 196
Shepmaster Avatar answered Aug 03 '26 19:08

Shepmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!