Learning Rust 3
Introductions
- introductions of two students
Learning Rust, Section 9
We are using The Rust Programming Language and rustlings.
Error handling
Rust does not have exceptions. Instead, it has:
Result<T, E>
for recoverable errors- panic! for unrecoverable errors
Panic
Panic prints a failure message, unwinds (cleans up the stack), and quits. You can display the call stack by setting an environment variable.
This will cause a panic:
Errors
Rust includes a Result enum:
Here is an example of how to use it:
Note, instead of a panic, here, you could have an interface that asks the user to choose a different file.
Exercises
Complete the rustlings exercises for section 13, numbers 1-3. Numbers 4-6 contain advanced material.
Learning Rust, Section 10
Generic data types
Rust has generic data types, which allow a function to operate on a type that is not known in advance.
For example, this function can find the largest value in vector of numbers or characters:
You can also use generics when defining types, such as a Point
that can handle
integer and floating point coordinates, and each coordinate can have a different
type:
Likewise, you can use generics in methods:
Here, the function x()
is defined on Point
and it returns a reference to
x
, which is of type T
.
Traits
Rust uses traits to
constrain types in a generic definition to ensure they implement some desired
functionality. For example, this Summary
trait indicates that a type should
have a summarize()
function:
Now we can define different types (as structs) that implement the Summary
trait:
Assuming the above is in a library crate called aggregator
, we can use it in
our main function:
Binding traits
You can require a type implement a trait. For example, the notify()
function
below requires an item that implements the Summary
trait:
You can do this with a longer-form notation as well:
These are equivalent!
You can specify multiple traits this way:
or with a where
clause:
Exercises
You are now ready to do rustlings section 14 on generics and 15 on traits.