Rust 101: Traits and implementations

Mukundh Bhushan
3 min readJul 9, 2020

--

In the previous article, we discussed about Structures in rust. Now let’s dive into traits and implementations.

TL;DR

  • What are Traits and implementations?
  • Implementation
  • Using functions in an impl
  • Traits

First, let’s start off by creating a new project called “implt” using the following command.

cargo new impt --bin

What are Traits and implementations?

Traits can be considered as interfaces in OOPs languages. Interfaces are for classes, traits are used along with structures, as they are similar interfaces, they contain only declaration no definition.

Implementations: as the term suggests they are implementations of a structure or trait i.e. definition of the functions. An implementation can be defined without the need of a trait.

Note:
Implementation must be the same name as the structure defined, but trait can have any name.
Implementation of a trait is not mandatory. It can be defined and never used. But when the trait is implemented all the function under it must be defined.

Implementation

Let us start off with implementation. Let's first create a structure called “Number” for the implementation an addition and subtraction function.

Here is the syntax:

impl <struct name>{   fn <function name>(&self,<args>){      //code
}
}

The “&self” tells rust that this function can be called by the structure’s instance.

Using functions in an impl

If you want to one of your function to pass a value to a function in the impl, the function cannot be in the impl declaration even if the function has “&self”

Instead the function needs to be defined outside the impl.

Traits

Let add more functionalities to our calculator using traits.

Here is the syntax

trait <trait name>{  fn <function name>(<args>);
}
impl <trait name> for <Structure name>{ fn <function name>(&self,<args>){ //code
}
}

The “&self” must be used while defining the function. Once the trait is being implemented all the functions must be defined but you can use which ever you want.

Notice how the “div” was not called but the code still executed. If “div” was not defined it will throw an error.

In the next article, we will discuss about Enumerators.

link to the next article

//yet to be written hold on tight

Link to the previous article

--

--