3 Basic Types
Familiarize yourself with basic types in Rust and when they may be used.
In R everything is a vector. A vector is a collection of values. There is no scalar type for a double/ character / integer / logical vector. Those are just length 1 vectors.
In Rust, however, scalars are the building blocks of everything. When a collection is needed those are made directly from scalars. You will often hear of these as primitives.
Today we will only be using a handful of these primitives but it is important to understand what they are—in general.
Integers
Integers are either signed or unsigned.
A signed integer can contain a negative value. Whereas an unsigned integer can contain only positive numbers.
- Signed Integers:
i8
,i16
,i32
,i64
,i128
- Unsigned Integers:
u8
,u16
,u32
,u64
,u128
In R, an integer vector is comprised of i32
values.
The letter prefix is the type of primitive. The following number indicates how many bits can be used to store the values. Unsigned integers can contain more possible values because they do not have to support negative numbers.
i32::MAX // 2147483647
u32::MAX // 4294967295
Floating point
In many cases where we need to do math we will use a floating point number. Floating points are signed and allow for decimal values.
There are two types: f32
and f64
.
In R, a double vector is comprised of f64
values.
Strong typing
Rust will infer a value’s type exceptionally well! However, we may want to specify the type manually as well. We can do this 2 primary ways:
- In assignment using
:
for examplelet x: f64 = 10;
- Or by specifying the suffix e.g.
10f64
or10_i32
You can use _
as a visual separator when specifying numbers in Rust. The following are all identical values:
let x: i32 = 1000;
let x = 1000i32;
let x = 1_000_i32;
Type casting
In Rust, math expressions can only be performed between like-types. You cannot add 2.0 + 3_f64
. To accomplish this we must cast to the same types.
Primitive types can be cast into one another using the as
keyword. To add an f64
to an i32
we should ensure they’re the same type.
fn add2(x: f64, y: i32) -> f64 {
+ y as f64
x }
Unit type
In Rust there is no concept of NULL
. Instead there is the unit type which is represented as ()
.
The unit type is technically a tuple without any fields. If the internet is to be believed it is called “unit” becaue it can only have one value and is related to the “singleton” or unit set in set theory.
Functions that do not return anything technically return ()
.
Exercise
Modify src/main.rs
to add two or more incompatible types.
- Define a variable
x
to be anf64
value - Define
y
to be ani32
value - Add them up and store them in the variable
z
- Use
println!()
to print the value ofz
Solution
View solution
fn main() {
let x = 3.14;
let y = 47_i32;
let z = x + y as f64;
println!(" The value of z is {z}");
}