Learning Rust 2
Introductions
- introductions of two students
Learning Rust, Section 6
We are using The Rust Programming Language and rustlings.
Enums
You can declare enumerated types:
…and then create instances of those types:
You can include data in enumerated types:
You can even mix types:
Option
Option
is an numerated type in the standard library, letting you define a
variable as being something or nothing.
See this amazing quote from Tony Hoare, who invented null
:
I call it my billion-dollar mistake. At that time, I was designing the first comprehensive type system for references in an object-oriented language. My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.
Rust forces you to allow for the possibility that something may be null, and then handle the case when it is null.
match
The match
expression lets you handle different cases for an enumerated type:
Exercises
You are now ready to do the rustlings
for section 8.
Learning Rust, Section 7
Packages and Crates
-
A crate can be a binary crate or a library crate.
-
A package contains one or more crates.
-
A package can contain/create many binary crates but only one library crate.
Modules
See the modules cheat sheet to see how Rust uses modules to organize source code.
- Code within a module is private from its parent modules by default.
- You can declare modules and functions public.
Note, you need to declare the hosting
module public and the
add_to_waitlist()
function public so that you can use them in the parent
module.
Use keyword
The use
keyword brings paths into scope:
The above is the idiomatic way to bring in a module — keep the module name instead of bringing the function into scope.
Here is the idiomatic way to bring in a struct:
External packages
To use an external package, list the package in your Cargo.toml
:
Then use it:
Separating modules
You can separate modules in to different file and follow some Rust conventions. For example:
src/lib.rs
:
src/front_of_house.rs
:
Exercises
You are now ready to do the rustlings
for section 10.
Learning Rust, Section 9
Vectors
Rust has support for vectors:
You can iterate over them:
Strings
A variety of ways to initialize a string:
You can add to a string:
Strings can store UTF-8 characters:
This means a string is not just a simple storage of one byte per character.
Exercises
You are now ready to do the rustlings
for sections 5 and 9.