Rust for the Novice Programmer/Numbers and data types
Numbers and data types
editBasic explanation of number representation
editOne thing to keep in mind is that at a fundamental level, all computers are doing are moving 1s and 0s around. We call a single value a 'bit'. Normally, computers are built to work in sections of 8 bits at a time and each one is called a 'byte'. The specifics of this aren't relevant right now, except that the number types in Rust are built using these bytes. The default number type is 'i32'. The i stands for integer, where an integer is a whole number(positive or negative), and the 32 is the number of bits used to represent this number, which is equivalent to 4 bytes. The integer types in Rust are 'i8', 'i16', 'i32' and 'i64', for each the number corresponds to the number of bits in it. There's also what are called unsigned integers which are integers that only represent positive values(including 0). Correspondingly, they are 'u8', 'u16', 'u32' and 'u64'.
Remember earlier where we said division was a little strange? How when we did 15/6 we got 2 out instead of 2.5? This is the reason, since the two numbers involved in the division are integers, the output will be an integer too. Since an integer can only store whole numbers, the output will not store the .5 extra. If we want values that can store decimals we use what are called floating-point numbers. These are numbers that store decimal values in them. In Rust, there are two floating point types, 'f32' and 'f64'. You can get a floating point easily by adding a .0 after a number. Note that the default floating-point type will be f64 in this case
For example:
fn main() {
let number = 15.0 / 6.0;
println!("{}", number);
}
Now the output we get is 2.5 as expected.
How do we choose a specific type that we want? We can do this by adding a colon then the type after the name as shown here:
let number: i16 = 3 + 4;
println!("{}", number);
Here we are using a 16-bit integer to store the value 7 then print it.
Why do we want different types?
Rust is a language that allows you as the programmer quite a lot of control over what you are doing. Using smaller number types as needed can save space since fewer bits are used.