Code Logo

Invert with ! Operator

Published at25 Jul 2026
Rust Functions Easy 0 views
Like0

Write a Rust function that takes a boolean value and returns its inverse using the ! (not) operator. The ! operator is Rust's logical NOT operator, which flips true to false and false to true.

The ! operator in Rust works on boolean types and returns a boolean. It is a prefix unary operator with high precedence. Unlike some languages that use different operators for bitwise and logical NOT, Rust uses ! for both contexts (though bitwise NOT for integers is done differently via the ! trait).

Boolean operations are fundamental to control flow in Rust. The ! operator is commonly used in while loops, if conditions, and assert macros to invert conditions. Understanding boolean algebra with !, &&, and || is essential for writing clear Rust code.

Time complexity is O(1) as the ! operator is a single CPU instruction. Space complexity is O(1). The operator has no runtime overhead as it compiles to a simple bitwise NOT instruction.

Edge cases include the operator working correctly on both true and false values, ensuring the function returns the correct inverted value for each input, and understanding that ! applies only to boolean types in Rust (not integers like some languages).

Example Input & Output

Example 1
Input
true
Output
false
Explanation

Invert again

Example 2
Input
false
Output
true
Explanation

Invert again

Example 3
Input
true
Output
false
Explanation

Not true is false

Example 4
Input
false
Output
true
Explanation

Not false is true

Example 5
Input
true
Output
false
Explanation

Final check

Algorithm Flow

Recommendation Algorithm Flow for Invert with ! Operator
Recommendation Algorithm Flow for Invert with ! Operator

Solution Approach

fn solution(val: bool) -> bool {
    !val
}

Best Answers

rust - Approach 1
fn solution(val: bool) -> bool {
    !val
}