Lesson 3
Lesson 3
Types
Data Types -Rust book
The Rust compiler can infer the types that you are using, given the information you already gave
it.
Scalar Types
A scalar type represents a single value. Rust has four primary scalar types:
integers
floating-point numbers
booleans
characters
Integers
For example
u8, i32, u64 language-rust
Floating point
Rust also has two primitive types for floating-point numbers, which are numbers with decimal
points. Rust’s floating-point types are f32 and f64 , which are 32 bits and 64 bits in size,
respectively.
The default type is f64 because on modern CPUs it’s roughly the same speed as f32 but is
capable of more precision. All floating-point types are signed.
boolean
The boolean type or bool is a primitive data type that can take on one of two values, called true
and false . (size of 1 byte)
char
char in Rust is a unique integral value representing a Unicode Scalar value
Note that unlike C, C++ this cannot be treated as a numeric type.
Other scalar types
usize
usize is pointer-sized, thus its actual size depends on the architecture your are compiling your
program for
As an example, on a 32 bit x86 computer, usize = u32 , while on x86_64 computers, usize =
u64 .
usize gives you the guarantee to be always big enough to hold any pointer or any offset in a
data structure, while u32 can be too small on some architectures.
Rust states the size of a type is not stable in cross compilations except for primitive types.
Compound Types
Compound types can group multiple values into one type.
tuples
arrays
struct
Tuples
Example
fn main() { language-rust
let x: (i32, f64, u8) = (500, 6.4, 1);
Struct
struct User { language-rust
name : String,
age: u32,
email: String,
}
Collections
Vectors
let names = vec!["Bob", "Frank", "Ferris"];
We will cover these in more detail later
Strings
Based on UTF-8 - Unicode Transformation Format
Two string types:
&str a view of a sequence of UTF8 encoded dynamic bytes, stored in binary, stack or heap.
Size is unknown and it points to the first byte of the string
String: growable, mutable, owned, UTF-8 encoded string. Always allocated on the heap.
Includes capacity ie memory allocated for this string.
A String literal is a string slice stored in the application binary (ie there at compile time).
String vs str
String - heap allocated, growable UTF-8
&str - reference to UTF-8 string slice (could be heap, stack ...)
String vs &str - StackOverflow
Rust overview - presentation
Let's Get Rusty - Strings
Arrays
Rust book definition of an array:
"An array is a collection of objects of the same type T , stored in contiguous memory. Arrays are
created using brackets [] , and their length, which is known at compile time, is part of their type
signature [T; length] ."
Array features:
An array declaration allocates sequential memory blocks.
Arrays are static. This means that an array once initialized cannot be resized.
Each memory block represents an array element.
Array elements are identified by a unique integer called the subscript/ index of the element.
Populating the array elements is known as array initialization.
Array element values can be updated or modified but cannot be deleted.
Array declarations
language-rust
//Syntax1: No type definition
let variable_name = [value1,value2,value3];
// Mutable array
let mut arr_mut:[i32;5] = [1,2,3,4,5];
// Immutable array
let arr_immut:[i32;5] = [1,2,3,4,5];
To make your code more readable you can use underscores with numeric literals
e.g.
1_234_567_890
ASCII code literals
Byte literals can be used to specify ASCII codes
e.g
b'C'
As you can see the final line in the function acts as a return from the function
Typically the return keyword is used where we are leaving the function before the end.
Loops
Range:
inclusive start, exclusive end
for n in 1..101 {}
inclusive end, inclusive end
for n in 1..=101 {}
inclusive end, inclusive end, every 2nd value
for n in (1..=101).step_by(2){} language-rust
We have already see for loops to loop over a range, other ways to loop include
loop - to loop until we hit a break
while which allows an ending condition to be specified
See Rust book for examples.
Control Flow
If expressions
See Docs
The if keyword is followed by a condition, which must evaluate to bool , note that Rust does not
automatically convert numerics to bool.
if x < 4 { language-rust
println!("lower");
} else {
println!("higher");
}
Note that 'if' is an expression rather than a statement, and as such can return a value to a 'let'
statement, such as
fn main() { language-rust
let condition = true;
let number = if condition { 5 } else { 6 };
Note that the possible values of number here need to be of the same type.
We also have else if and else as we do in other languages.
Printing
println!("Hello, world!"); language-rust
Match Example
enum Coin { language-rust
Penny,
Nickel,
Dime,
Quarter,
}
Windows
See details here
download and run rustup-init.exe .
Other methods
Cargo
See the docs
Cargo is the rust package manager, it will
download and manage your dependencies,
compile and build your code
make distributable packages and upload them to public registries.
Some common cargo commands are (see all commands with --list):
build, b Compile the current package
check, c Analyse the current package and report errors, but don't build object files
clean Remove the target directory
doc, d Build this package's and its dependencies' documentation
new Create a new cargo package
init Create a new cargo package in an existing directory
add Add dependencies to a manifest file
run, r Run a binary or example of the local package
test, t Run the tests
bench Run the benchmarks
update Update dependencies listed in Cargo.lock
search Search registry for crates
publish Package and upload this package to the registry
install Install a Rust binary. Default location is $HOME/.cargo/bin
uninstall Uninstall a Rust binary
See 'cargo help ' for more information on a specific command.
Useful Resources
Rustlings
Rust by example
Rust Lang Docs
Rust Playground
Rust Forum
Rust Discord