0

Rust – Function that accepts Struct Instance that implements a specific Trait

This post briefly tackles how to create functions that accept struct instances that implement a specific trait.

From Java Perspective

In Java, this would mean something like:

Interfaces

Rust does not have interfaces but has traits.

Implementations

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

Usage

There are two (2) methods – toss  and inflate. BasketBall  instances can be passed to both methods; while TennisBall  instances can only be passed to toss .

This outputs:

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

In Rust

Traits

Implementations

First, we make BasketBall both Bouceable and Inflatable.

Second, we make TennisBall Inflatable only.

Usage

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 invoking  invoking other methods on the same instance. For example:

Karl San Gabriel

Karl San Gabriel

Professional Software Developer