The first few lines of code are usually declaration. let num = 0
. Most of the time you don't put too much thought on which integer type to choose or indicate, it's like you are on autopilot. When declaring a variable let num = 0;
, you expect the compiler to add the type, and also indicate that the variable is immutable. Lets switch off auto pilot and understand what let num: i32 = 1;
mean.
By default as stated in the book, variables are immutable.
- Immutable means can not be changed (
Read-Only
). - Mutable, can change (
Read
andWrite
).
Coming from other languages if a variable can't change, you might think of a constant (const). The difference between constant and immutable variable:
const SEVEN: i32 = 7; // constant
let seven = 7; // immutable variable
let mut six = 6; // mutable variable
Constant
- const needs to have an SNAKE_CASE uppercase name, else you get a warning
constant `seven` should have an upper case name
. - const needs you to specify the type(see error below).
- const will never be mutable, meaning you can't add the
mut
keyword.
error: missing type for `const` item
--> src/main.rs:1:7
|
1 | const SEVEN = 7;
| ^^^^^ help: provide a type for the constant: `SEVEN: i32`
Immutable
- You are not forced to specify the type, if you omit the type the compiler will assist.
- immutable can be converted to mutable by adding the
mut
keyword. - Looking at the rust naming conversion, the variable is always snake_case lowercase.
A constant needs you to always specify a type, be it integers or tuples even arrays. Looking at integers, there are multiple types, such as i8
, u32
, etc.
Before choosing an integer, you need to understand that Rust has signed i
and unsigned u
types.
- Signed
i
types accept both positive(+) and negative(-) values, depending on the bits you selected. - Unsigned
u
only accepts positive(+) values.
Next to i
or u
are the bits, so 8-bits
, 32-bits
, and etc. The bits indicate the storage capacity e.g u8
stores values from 0 to 255, above that results to the error below.
error: literal out of range for `u8`
--> src/main.rs:3:17
|
3 | let x: u8 = 256;
| ^^^
|
= note: `#[deny(overflowing_literals)]` on by default
= note: the literal `256` does not fit into the type `u8` whose range is `0..=255`
There's also usize
and isize
, which is dependent on the size of your machine architecture. So if running a 32-bit
machine, usize
can be u32 (32-bits). There are other types such as floats(f32
and f64
), boolean(bool
), arrays([1, 2, 3]
), and more.
Top comments (0)