Traits
Systems in Rust
Preamble
You know what a queue is. Now make one in Rust.
Design Decision
- With the addition of a queue, you get to decide:
- Whether to head push and tail pop, or…
- Whether to tail push and head pop.
- This is the added difficulty incurred by adding a queue.
Review: Box
- To put some
xin aBox, simply:
- To remove
xfrom the `Box, simply use the special “unary asterisk” operator, also called “dereference”.
Novel: Generics
- You are welcome to read Rustbook on Generics
- We previously “hard-coded” the
Stackto accept strings.
- We instead append a type annotation to the end of stack, like so:
- By convention, Rust uses
Tto refer to a type variable. - Then, within the declaration we may refer to
T:
- Upon making this change, you will get a series of
rustccomplaints about not specifying types in a variety of locations. - You will have relatively little difficulty working through these, and should learn something valuable in the process.
Novel: Traits
- It is customary for programmers with a background in object-oriented langauges, such as Python, JavaScript, or Java, to have an affinity for methods.
- In the lab, we used functional style:
- Now we will use traits to implement methods to get the following style:
- It is not required to use traits to achieve this, and possible to write methods directly, I simply found this uninteresting.
- Have two parts:
- A declaration:
- An implementation:
- An astute observer will notice that
Toccurs seven (7) times just within the declarations.- Form your own opinion about that.
Starter Code
src/main.rs
- I am providing a fairly enormous testing script via Gist.
- I have removed
dbg!()calls and simply check popped values.