Skip to content

Scalar Types

Jens Kristian Hoel edited this page Aug 29, 2022 · 4 revisions

Numbers

Note that for Integers i32 is default, but for floats f64 is default because it will have more precision. f64 can be really slow on non-64 bit architectures!

Min/Max values of integer types:

i8 = -256/256
i16 = -32768/32768
i32 = -2147483647/2147483647
i64 = -9223372036854775807/9223372036854775807
i128 = -170141183460469231731687303715884105727

the unsigned equivalents like u8, u16 etc. will be only the positive portion:

u8 = 0/256
u16 = 0/32768
..etc.

This means that unsigned values can be held using less memory, as they fit

The values can also be found with:

fn main() {
    println!(" i8 has the min value of {}.", i8::min_value());
    println!(" i8 has the max value of {}.", i8::max_value());
    println!(" i16 has the min value of {}.", i16::min_value());
    println!(" i16 has the max value of {}.", i16::max_value());
    ...etc
    println!(" i128 has the min value of {}.", i128::min_value());
    println!(" i128 has the max value of {}.", i128::max_value());
}

usize and isize

These types have the same number of bits as the platforms pointer type. usize can represent every memory address in the process. The maximum isize value is the upper bound of object and array size and this ensures that isize can be used to calculate differences between pointers and access every byte within a value like a struct.

Integer Literals

Decimal		- 1000000
Hex		- 0xdeadbeef
Octal		- 0o77543211
Binary		- 0b11110011
Byte (u8 only)	- b'A'

"Most people just use a decimal integer between 0 and 255. The terms u8 and byte are used interchangeably in Rust. You will hear byte all the time instead of u8"

The representations that take more than one digit can have any number of ignored underscores in them. So for convenience, we could write the above table as:

Decimal		- 1_000_000
Hex		- 0xdead_beef
Octal		- 0o7754_3211
Binary		- 0b1111_0011

Characters

A char is always 4 bytes (32 bits), and that makes an array of characters effectively an UTF-32 string. Character literals are specified using single quotes:

let my_letter = 'a';

The Char type is pretty much useless. Strings are UTF-8 and characters are not, so they do not use chars internally. Source files are also UTF-8, so chances are when you want to deal with a single character it's going to be a UTF-8 string not a character literal.

Clone this wiki locally