Function
Example of function.
src/03-function/main.rs
fn main() {
let x = 3;
let y = 4;
let result = add(x, y);
println!("{x} + {y} = {result}");
}
fn add(input1: i32, input2: i32) -> i32 {
input1 + input2 // notice the omission of `;` at the end.
// last statement implicitly returns, and equivalent to
// return input1 + input2;
}
danger
In the above example, ff we assign x
, and y
both to be 2147483647
(max
i32
), the result will overflow i32
range. Unfortunately, such errors are not
caught compile time.
Check out helper methods: wrapping_add, saturating_add, overflowing_add, checked_add.
Calculate area of a circle
Another example where we calculate area of a circle with the input radius given by the user.
src/03-circle-area/main.rs
use std::io;
fn main() {
println!("Enter radius: ");
let mut radius = String::new();
io::stdin()
.read_line(&mut radius)
.expect("Failed to read input!");
let radius: f64 = radius.trim().parse().expect("Please type a number!");
const PI: f64 = 3.14159;
let area = PI * radius * radius;
println!("Area = {area}");
}