Arithmetic Operators
Part of the Fundamentals section of Coddy's Rust journey — lesson 15 of 75.
Operators are used to perform operations on values.
First we will discuss the most basic arithmetic operators, they may be familiar from math classes.
| Operator | Operation | Example |
|---|---|---|
| + | Addition | 3 + 2 = 5 |
| - | Subtraction | 3 - 2 = 1 |
| * | Multiplication | 3 * 2 = 6 |
| / | Division | 4 / 2 = 2 |
Let's see usage example,
let a: i32 = 3;
let b: i32 = 5;
let c: i32 = a + b
// c holds 8When working with decimal numbers in Rust, we use the f64 data type, which can store numbers with decimal points. The same arithmetic operators (+, -, *, /) work with f64 just like they do with integers:
let x: f64 = 3.3;
let y: f64 = 4.1;
let z: f64 = x + y;
// z holds 7.4Challenge
BeginnerWrite a code that initializes two variables, a and b, with the values 5.2 and 2.6 (respectively).
After that, initialize another variable c that will hold the result of a / b.
Cheat sheet
Arithmetic operators perform mathematical operations on values:
| Operator | Operation | Example |
|---|---|---|
| + | Addition | 3 + 2 = 5 |
| - | Subtraction | 3 - 2 = 1 |
| * | Multiplication | 3 * 2 = 6 |
| / | Division | 4 / 2 = 2 |
Using arithmetic operators with integers:
let a: i32 = 3;
let b: i32 = 5;
let c: i32 = a + b;
// c holds 8Using arithmetic operators with decimal numbers (f64):
let x: f64 = 3.3;
let y: f64 = 4.1;
let z: f64 = x + y;
// z holds 7.4Try it yourself
fn main() {
// Type your code below
// Don't change the line below
println!("a = {}, b = {}, c = {}", a, b, c);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input