From the course: Rust Essential Training

Unlock the full course today

Join today to access over 22,500 courses taught by industry experts or purchase this course individually.

Generic method definitions

Generic method definitions - Rust Tutorial

From the course: Rust Essential Training

Start my 1-month free trial

Generic method definitions

- [Instructor] In addition to using generics to represent the data types of fields within a struct, we can also use generics when implementing methods for a struct. When defining the implementation block for our rectangle struct, which has two generic variables T and U, we'll need to include those two generic variables after the implement keyword. And we'll also need to include them after the name rectangle as well. Including T and U after the implement keyword hell's the rust compiler that will be implementing methods and functions for a rectangle with two generic types. And we'll see why that matters shortly. Next, let's define a method to get the rectangles width. The return type for that method will be whatever data type T is and we will return a reference to the width value. We have to return a reference here rather than the width variable itself. Because at this point, we don't know what data type T will be…

Contents