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:


Rust does not have interfaces but has traits.


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


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



First, we make BasketBall both Bouceable and Inflatable.

Second, we make TennisBall Inflatable only.


This outputs:

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

Tested using Rust 1.39.0.


  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