Primitive types
Firstly, there are the usual integer and floating point types. Instead of languages like C++, where you have to know how big an int
is (usually 32 bits) and use modifiers for additional types (an unsigned integer with a size of 128 bits is unsigned long long
), Rust directly incorporates those things inside the type names. This makes things clearer and is also useful for knowing how exactly a value is going to behave.
Of course, there's also a boolean type.
let unsigned_byte: u8 = 255;
let signed_byte: i8 = -128;
let unsigned_short: u16 = 65535;
let signed_short: i16 = -32767;
let unsigned_int: u32 = 4_294_967_295;
let signed_int: i32 = -2_147_483_648;
let unsigned_long: u64 = 18_446_744_073_709_551_615;
let signed_long: i64 = -9_223_372_036_854_775_808;
let unsigned_long_long: u128 = 340_282_366_920_938_463_463_374_607_431_768_211_455;
let signed_long_long: i128 = -170_141_183_460_469_231_731_687_303_715_884_105_728;
let float: f32 = 3.141_592_74;
let double: f64 = 3.141_592_653_589_793_1;
let boolean: bool = false;
Additionally, there are the usize
and isize
integer types. These correspond to the native size of the CPU. Additionally, usize
is used to index arrays and memory, but more on that later.
Now there is the char
type. People that know C++ might assume it to be an 8-bit integer type and try to use it as byte storage. In Rust, the tool for that particular job is u8
, as chars are 32 bits wide. That is because Rust actually natively supports unicode!
But isn't 32 bits for every single character pretty wasteful? It is, but chars are only really used when processing them one by one. There is a special type for strings, but more on that later.