The Rust Programming Language — Primitives — Floats and Immutability
In this article, we are going to learn about float
primitive type.
Floats are a primitive type in Rust which allow you to deal with numbers and decimals. Take for example below code snippet:
fn main() {
let x = 1.1;
let y = 2.2;
println!("x times y is {}!", x*y);
}
The code snippet looks fairly similar to the ones that we have used in string interpolation examples, with an additional steps of generating the result of x times y and also coverting it to the string to substitute the {}
for generating the final string output.
Typically, if we go by Maths, we should expect the output of x*y
to be 2.42
but the output we get in the console is 2.4200000000000004
. This is typically because all programming languages perform mathematical operations for decimals using binary system which is quite faster. Modern hardware, for decimal math, has a lot of overhead and multiple instructions which could take significant hit in performance.
There is also one more thing to note here is that println!()
is not actually a function call. It is called a macro
in Rust programming language. Any call that ends with !
is a macro
. A macro
is nothing but a line of code which subsequently get’s expanded into set of instructions which are…