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.
Return types with implemented traits - Rust Tutorial
From the course: Rust Essential Training
Return types with implemented traits
- [Instructor] We've used traits to set bounds on the generic data types that can be passed as arguments into a function. Now, let's look at how we can use traits in the other direction to set bounds on the type of data that can be returned by a function. Let's define a function that can return any data type as long as it implements the display trait. Since we'll be referencing the display trait for this program, we'll first need to import the format module at the top of the code. Then we'll define a new function named get displayable. It doesn't have any input parameters, but it will have a return value. We'll specify a return type that can be anything as long as it implements display. And we do that by typing impl display. This type of syntax for a parameter using the implementation keyword can be used in some situations as an alternative to the trait bound syntax we saw in the previous videos. For simplicity, let's…
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)
-
-
-
-
-