Data Types
Last updated
Last updated
Rust is statically-typed (like Java), but (unlike Java) it generally infers the types. If many types are possible (like when using parse
), then we have to specify the type. With that, let's discuss the various types!
Many languages have a single integer type. Not Rust! Rust has five different integer types based on the length and whether they are signed (possibly negative) or unsigned (always positive):
What should you default to? Probably i32
. It's what Rust defaults to and is generally the fastest, even on 64-bit systems.
What can you enter as an integer? Any of the following options!
Floating point numbers are a bit simpler. There are only two types: f32
and f64
. In this case, the Rust default is f64
.
Just like most other languages, Rust has a boolean type that has two possible values: true
or false
.
char
represents a Unicode Scalar Value, which means it can represent more than just A-z. Here's an example:
A tuple groups together any number of values with random types. Here are some examples
What happens if you go out of bounds?
Arrays are similar to tuples but every element must have the same type. In Rust, once an array is created, it cannot grow or shrink. Here's an example of a common use for arrays:
Unlike tuples, you cannot easily destructure arrays via pattiern matching. But you can get the element at the index like so:
Unlike the tuple out-of-bounds message, if you go out of bounds with an array, the message is very clear:
Since the index starts at zero, it must always be one less than the length. So this error message is telling us we are going one too far!
Length
Signed
Unsigned
8-bit
i8
u8
16-bit
i16
u16
32-bit
i32
u32
64-bit
i64
u64
arch
isize
usize
Number literals
Example
Decimal
98_222
Hex
0xff
Octal
0o77
Binary
0b1111_0000
Byte (u8
only)
b'A'