![]() |
Rust is a systems programming language with a concept of Interfaces in Rust that is implemented by Traits.Trait in Rust is basically a struct having no bodies for the methods. The logic is generally not defined but only the methods are. Rust enforces us to follow a set of coding practices with implementing the interface. Anyone having a background in OOP languages like C++ or Java can easily draw an analogy between interfaces in OOPS and Rust’s way of implementing interface as a trait. Interfaces in Rust help in building ‘Has A relationship’ applications as they are loosely coupled. Syntax:Abstract methods are empty methods while Concrete methods are regular methods
Trait methods have &self parameter defined as the first parameter for the methods. For specifying any extra parameters, we need to specify them after the self-parameter declaration. Defining a Trait as an interface:
Here, the Trait GeeksforGeeks is implemented with an abstract method (single defined). Example 1: Rust
Output: ![]()
In this example, we define two structs Courses and DSAPractice. Then, we define a trait GeeksforGeeks and also nest a function gfg inside it with self parameter. Implementing GeeksforGeeks traits for Courses and DsaPractice Traits. Example 2: Rust
Output: ![]()
Explanation: In this example, we declare structs for courses and practice and then implement the traits Geeksforgeeks for structs Practice and Courses. Example 3: Rust
Output: ![]()
Explanation: In the example above, we add a trait called OtherWebsites with a method of other websites(). Here, we call courses.otherwebsites() method. Next, we define the traits GeeksforGeeks and other websites and pass (&self) parameters in them as well. Next, use the impl function to declare the traits. |
Reffered: https://www.geeksforgeeks.org
Rust |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 17 |