0

Function Accepts Struct That Implements A Trait

Last Updated on

This post is about functions that accept struct instances that implement a specific trait.

Function, Struct, and Trait From Java Perspective

If this for Java, the title would be “Method Accepts Class That Implements An Interface”.

Interfaces

We would have the following interfaces to implement.

Interface Implementations

We have 2 classes – BasketBall and TennisBall. Both balls bounce but only one of them is inflatable.

Usage

There are two 2 methods – toss and inflate. The codes pass BasketBall instances to both methods but can only pass TennisBall instances to the toss method.

The codes generate this output.

If we uncommented the last time, we would have a compilation error.

"Function Accepts Struct That Implements A Trait" in Java

In Rust

Traits

Rust does not have interfaces. Instead, they have traits.

Trait Implementations

First, we make BasketBall both Bouceable and Inflatable.

Second, we make TennisBall Inflatable only.

Usage

We have generic functions that accept structs of  T parameter type.

This outputs:

If we try to use the last time, we will have a compilation error.

Tested using Rust 1.39.0.

Errata

  1. Changed self to &self. Using &self  is recommended to avoid error[E0382]  when calling other functions in the same instance. For example:

Avatar

Karl San Gabriel

Professional Software Developer