Invert with ! Operator
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
Invert again
Invert again
Not true is false
Not false is true
Final check
Algorithm Flow
Solution Approach
Negate a boolean value using the ! (not) operator. This operator converts the operand to a boolean and inverts it. If v is true, !v is false. If v is false, !v is true. For non-boolean values, the operator first coerces them to boolean: falsy values become true when negated.
The ! operator is the logical NOT in Rust. It works with the bool type directly. For non-boolean types you would need to convert using != or match patterns.
Time complexity is O(1), space complexity is O(1).
Best Answers
fn solution(val: bool) -> bool {
!val
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
