[Avg. reading time: 5 minutes]
Unary Operators in Rust
Unary operators operate on a single operand.
In Rust, unary operators are used for:
- Negation
- Boolean inversion
- Pointer dereferencing
- Borrowing (references)
Common Unary Operators
| Operator | Name | Purpose |
|---|---|---|
- | Negation | Negates a numeric value |
! | NOT | Inverts a boolean value |
* | Dereference | Accesses the value behind a reference |
& | Borrow | Creates an immutable reference |
&mut | Mutable Borrow | Creates a mutable reference |
Negation Operator (-)
Used to negate numeric values.
fn main() { let x = 5; let y = -x; println!("y: {}", y); }
- Works only on numeric types
- Does not mutate the original value
Logical NOT (!):
Inverts a boolean value.
fn main(){ let a = true; let b = !a; println!("b: {}", b); }
Borrow (&):
Creates an immutable reference to a value.
fn main(){ let s = String::from("hello"); let r = &s; println!("r: {}", r); }
- Ownership is not transferred
- Multiple immutable borrows are allowed
- The value cannot be mutated through r
Mutable Borrow (&mut):
fn main(){ let mut s = String::from("hello"); { let r = &mut s; r.push_str(", world"); } println!("s: {}", s); }
- Only one mutable borrow at a time
- No immutable borrows while mutable borrow exists
- Enforced at compile time
Dereference Operator (*)
Accesses the value behind a reference.
fn main() { let x = 10; let y = &x; let z = *y; println!("z: {}", z); }
- y holds the address of x
- *y reads the value at that address