Rust
Beginner
1 min read
Data Types and Control Flow
Example
fn main() {
// Integer and float types
let x: i32 = -42;
let y: f64 = 3.14;
let big: u128 = 340_282_366_920_938_463_463_374_607_431_768_211_455;
println!("x={x} y={y} u128_max≈{big}");
// if as an expression
let abs_x = if x < 0 { -x } else { x };
println!("|{x}| = {abs_x}");
// Tuple and array
let point: (i32, i32) = (10, 20);
let rgb: [u8; 3] = [255, 128, 0];
println!("point = ({}, {})", point.0, point.1);
println!("red channel = {}", rgb[0]);
// loop with a return value
let mut attempts = 0;
let result = loop {
attempts += 1;
if attempts == 3 {
break attempts * 10;
}
};
println!("loop returned {result} after {attempts} attempts");
// for with a range and iterator adapters
let sum: i32 = (1..=100).filter(|n| n % 2 == 0).sum();
println!("Sum of even numbers 1..=100 = {sum}");
// while loop
let mut n = 1u64;
while n < 1_000 {
n *= 2;
}
println!("First power of 2 >= 1000: {n}");
}