Rust arithmetic operator
Created By: chatGPT
Rust offers a set of arithmetic operators that allow you to perform mathematical operations on numeric types. The main arithmetic operators include addition, subtraction, multiplication, division, and modulus. Here's a breakdown of each operator:
Addition (+) is used to add two numbers together.
let sum = 5 + 3; // sum is 8
Subtraction (-) is used to subtract one number from another.
let difference = 5 - 3; // difference is 2
Multiplication (*) is used to multiply two numbers.
let product = 5 * 3; // product is 15
Division (/) is used to divide one number by another. In Rust, dividing two integers performs floor division.
let quotient = 5 / 3; // quotient is 1
Modulus (%) returns the remainder of a division operation.
let remainder = 5 % 3; // remainder is 2
Each operator can be used directly on variables as well. For example:
let a = 10;
let b = 2;
let add = a + b; // add is 12
let sub = a - b; // sub is 8
let mul = a * b; // mul is 20
let div = a / b; // div is 5
let mod = a % b; // mod is 0
It's also important to note that Rust has certain type behaviors. For instance, when you attempt to divide integers, you will encounter an error if you're trying to divide by zero.
In summary, Rust's arithmetic operators are essential for performing calculations efficiently and safely, ensuring you handle scenarios like division by zero appropriately.let x = 5;
let y = 0;
let result = x / y; // This will cause a panic at runtime!