Learn / Rust / Types and functions: a unit converter
Rust, lesson 3 of 5
Types and functions: a unit converter
Every value in Rust has a type. The common ones:
i32: whole numbers, such as 42 or -7f64: numbers with a decimal point, such as 9.5bool:trueorfalse&strandString: text
A function lists the type of each input, and -> shows the type it gives back. The last line, written without a semicolon, is the answer:
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
println!("{}", add(2, 3));
}
Here is a converter, as engineers use every day. {:.2} shows 2 decimal places:
fn mm_to_inches(mm: f64) -> f64 {
mm / 25.4
}
fn main() {
println!("{:.2}", mm_to_inches(100.0));
}
Rust will not quietly mix types. Adding a whole number to a decimal is refused until you convert one of them, which stops a whole class of rounding bugs:
fn main() {
let a: i32 = 5;
let b: f64 = 2.5;
println!("{}", a + b);
}Rust refuses to build this.