xgreed
xgreed

Reputation: 35

Evaluate a borrowed boolean

Is there any work around this?

Is it possible to evaluate a borrowed boolean? I'm quite new to rust so I probably didn't used the right terminology.

fn control(map: &[bool;5]) -> bool {
    let mut hold = false;
    for n in map.iter() {
        if n {
            hold = true;
            break;
        }
    }
    hold
}

Upvotes: 3

Views: 504

Answers (1)

user2722968
user2722968

Reputation: 16475

You can simply dereference n as in if *n { and it will compile. n is a &bool in your example, *n gives you a bool, which the compiler expects.

The shorter version of control would be

fn control(map: &[bool]) -> bool {
    map.iter().any(|e| *e)
}

The above takes a borrowed slice (&[bool]) instead of a fixed-size array as an input parameter; this is strictly more powerful since all arrays can be borrowed as a slice. The loop in your version is folded into the any() method that all iterators provide.

Upvotes: 5

Related Questions