Summary
-
Traits define behavior that can be implemented by many different types
-
You can put restrictions on type parameters by adding trait bounds
-
Trait bounds can be added for functions, impl blocks, and more
-
The
Display
trait is used byprintln!
,format!
, and related macros -
A number of common traits can be derived, so you don’t have to write them by hand
-
Clone
is a derivable trait that lets you make a copy -
Copy
is a derivable marker trait that tells the compilr, “It’s really cheap to clone" -
Debug
is a derivable trait that produces output useful for debugging your code -
PartialEq
andEq
control the==
and!=
operators -
PartialOrd
andOrd
control the four other comparison operators -
In order to use a trait, the trait must be in scope
-
You can bring a trait into scope with
use
-
You can place multiple bounds on a type parameter by using
+
-
Traits can define associated types
Get hands-on with 1400+ tech skills courses.