From the course: Rust Essential Training
Unlock the full course today
Join today to access over 22,600 courses taught by industry experts or purchase this course individually.
Trait bounds
- [Instructor] Although we've encountered them briefly in several earlier examples, I want to take a moment to more formally address the concept of trait bounds. When working with generics, you'll often need to use traits to serve as bounds to stipulate the functionality a type implements. Bounding restricts a generic to only data types that conform to those bounds so you can write functions that accept many different data types while also guaranteeing that the types it accepts will have the necessary behaviors for your function to use it. Consider the print_type function shown here on line three, which accepts an input item of some generic type T and then prints a message with its data type by using the any module's type_name function, which returns the name of a given type as a string slice. Since we're passing the input item as a parameter to the print line macro on line four, for this function to work, that given item…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
-
-
-
-
-
-
-
-
-
-
(Locked)
Implement traits4m 33s
-
(Locked)
Default trait implementation1m 33s
-
(Locked)
Derive traits3m 58s
-
(Locked)
Trait bounds3m 8s
-
(Locked)
Multiple trait bounds5m 16s
-
(Locked)
Return types with implemented traits3m 40s
-
(Locked)
Challenge: Implement the display trait1m 16s
-
(Locked)
Solution: Implement the display trait1m 53s
-
(Locked)
-
-
-
-
-