CS110L L5 - Traits and Generics

Warning
If someone is reading this blog, please be aware that the writer did not consider the experience of the other readers.
After all, the most important part is about writing things down for better memorization.
Traits
A trait defines the functionality a particular type has and can share with other types. We can use traits to define shared behavior in an abstract way. We can use trait bounds to specify that a generic type can be any type that has certain behavior.
- Traits are like what is called ‘interface’ in other languages, allowing programmers to define shared behavior or override default behavior.
Overriding Traits
For example, one can override the
Display
functionality in order to define the way an object gets print out:1
2
3
4
5
6
7
8
9
10
11
12
13impl fmt::Display for LinkedList {
fn display(&self, f: fmt::Formatter<'_>) -> fmt::Result {
let mut cur: &Option<Box<Node>> = &self.head;
let mut result = String::new();
while let Some(node) = cur {
result = format!("{} {}", result, node.value);
cur = &node.next;
}
write!(f, "{}", result);
}
}This way we can directly print out the linked list with
println!("{}", list)
macro.
Deriving Traits
One can derive some traits with reasonable default implementation on structs(objects). For example:
1
2
3
4
5
struct Point {
x: f64,
y: f64,
}For these four traits derived here for
Point
, they include the following meaning respectively:Debug
: allow printing out full debug info of the object of this type with specifier{:?}
PartialEq
: allow comparing variables of this same type using double equal signClone
: …Copy
: …
Generics
- TODO
- Title: CS110L L5 - Traits and Generics
- Author: Last
- Created at : 2025-05-06 20:30:02
- Link: https://blog.imlast.top/2025/05/06/cs100l-l5/
- License: This work is licensed under CC BY-NC-SA 4.0.