Rust
is a strongly typed language. The type of value defines the interpretation of the memory holding it and the operations that may be performed on the value. So let us familiarise ourselves with them.
1️⃣ Boolean
Rust implements Boolean as true
& false
.
|
|
2️⃣ Integer
Rust implements integers as either signed or unsigned. The names of these types usually is self explanatory. For example, u8
is Unsigned 8 bit Integer which means it can store a value from 0 to a maximum value of (2^8)-1 = 255. Other unsigned integers can fall into u16
, u32
, u64
, u128
, usize
categories.
Signed Integers go from a range of negative to positive integers through zero. They are usually denoted by i8
, i16
, i32
, i64
, i128
, isize
Interesting point to note here is that the types isize
and usize
have size that depends entirely on how many bytes it takes to reference any location in memory. Which means for a 32 bit target it’ll take 4 bytes (4 x 8 bits).
By default, the compiler will assume the integer is of size i32
, if it is not type annotated.
|
|
3️⃣ Floats
Rust implements floats which are type annotated as f32
or f64
. By default, the compiler assumes the type of float to be f64
.
One can differentiate between floating points and integers from the .
in the numbers.
|
|
4️⃣ Characters
Rust implements char
which are unicode scalar values which represents each characters in 4 bytes. unicode representation allows rust to use the char
type to annotate more than standard ASCII characters. So, something like let one = 1️⃣
is valid rust code.
|
|
⭐ Composite Types
The types that can group multiple values into one type are referred to as Composite or Compound types. Rust has 2 of these.
1️⃣ Tuple
tuple is a general way of grouping together a number of values with a variety of types into one compound type. Note : tuples have a fixed length which can be declared only once and can not be changed just like tuples in python.
|
|
Tuples in rust can be destructured using the following syntax:
|
|
Elements in tuples can be accessed using the dot syntax so t.0
will return 42
.
2️⃣ Array
collection of multiple values is with an array. Note : Every element of an array must have the same type. Note : Unlike list
in python rust arrays have a fixed length.
|
|
Size of an array can be declared after annotating the type
|
|
Rust allows a handy method of creating a array of arbitrary length with the same element (just like numpy.full(shape, value)
)
|
|
This is easier way of expressing let b = [1, 1, 1, 1, 1];
Indexing in rust is just as you’d expect with zero numerical indexing languages like C
or Python
.
a[0]
will return 1
If the keyword mut
is used while initialising the array, the values of these array can be reassigned.
That’s about the type system of Rust lang. To learn more visit the resources page from Rust::Oxidation