Boolean not !

! not bool boolean true false

There are several cases when we might want to negate the value of a boolean expression.

Two are shown here, let me know if you think about more distinct cases I should include here.

examples/boolean-not/src/main.rs

fn main() {
    let strings = vec!["foo", "", "bar"];
    for string in strings {

        // negate a boolean value
        if ! string.is_empty() {
            println!("string: {}", string);
        }
    }


    // Toggle
    let mut on = true;
    println!("on: {}", on);
    on = ! on;
    println!("on: {}", on);
    on = ! on;
    println!("on: {}", on);
}

Negate a boolean value

In the first case we have a method called is_empty that will return true if the string is empty. What if we would like to check for not empty ? There is no such function but we can just negate the value returned by is_empty:

if ! string.is_empty() {

Toggle

This is a bool, a boolean value. If it was true then after this operation it will be false and if it was false then after this operation it will be true.

I use such toggle in a game where I have various modes and each one can be turned on and off separately. So each one will have such a variable.

on = ! on;

Related Pages

Exclamation mark in Rust !

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo