Skip to main content

Command Palette

Search for a command to run...

Rust traits vs Java interfaces?

Updated
•2 min read•View as Markdown

What's common?

Interfaces and traits define an expectation from a piece of code.

Suppose you have the following requirement for a function:

  • Accept an object of a class.
  • Print an appropriate representation of that object to standard output.

Note: Representations are different for every class.

In a world where interfaces don't exist, you might end up with the following pseudo code.

function print_representation(a: <generic object type>) {
      if type(a) == type1 {
            print(Representation of type1 )
      } else if type(a) == type2 {
            print(Representation of type2 )
      }
      ....
}

But with interfaces, you can do the following.

function print_representation(a: <any object implementing PrintMe method>) {
   a.PrintMe()
}

This means there is expectation that the object must implement a method called PrintMe().

How traits are different from interfaces?

Traits can be added to existing types.

This means that we can extend the functionality of any type, even primitive ones.

Consider the following piece of Rust code.

trait GetType {
    fn print_type(&self) -> &str;
}

impl GetType for i64 {
    fn print_type(&self) -> &str {
        return "This is a number!"
    }
}

fn main() {
    let a: i64 = 32;

    println!("{}", a);
    println!("{}", a.print_type());
}

Which gives the following output.

32
This is a number!
  • Here we are defining a new trait that has a single function called print_type().
  • Then we implement that trait for a primitive type like i64 (signed 64-bit integer).

You can think of this as extending the functionality of an existing type.

The one thing to keep in mind here is that the scope of where this function (print_type) can be used completely depends on where in your source code the trait (GetType) is defined. That means you won't be able to use the new method in some other file that has no idea this trait even exists.

More from this blog

Utkarsh Bindal's Blog

30 posts

Curiously exploring user problems and their solutions.