Rust Lang

Rust Traits

A trait refers to a group of methods defined for a specific type. Traits are incredible as they provide an abstraction for functionality and logic that can be shared between multiple types.

Traits support concrete and abstract methods, as we will see in this article.

Rust Define Trait

To define a trait in Rust, we use the trait keyword, followed by the trait’s name and body. The trait body can contain either concrete or abstract method.

The syntax is as shown:

traitTraitName {
fnabs_method(&self);
fncon_method(&self) {
// function body
  }
}

Note that a trait method includes the &self parameter. This must be the first parameter in the method, and other parameters must be provided after.

trait Info {

fn description(&self) -> String;

fn mileage(&self) -> f64;

}

In the code above, we define a strait called Info that contains abstract methods. A car object can use the methods above. However, since the method of description and mileage values can differ depending on the car, the logic has to be applied distinctly.

Rust Implement Trait

After defining a trait, we can need to implement it. The syntax for trait method implementation is similar to a struct method.

Consider the example below:

traitInfo {
fndescription(&self) ->String;
fnmileage(&self) ->f64;
}
structVehicle {
    model: String,
    manufacturer: String,
    price: i32
}
impl Info for Vehicle {
fndescription(&self) ->String{
returnformat!("Model: {}, Manufacturer: {}, Price: {}", self.model, self.manufacturer, self.price);
    }
fnmileage(&self) ->f64 {
return10000.33;
    }
}

In the above example, we define a struct that holds information for a vehicle. We can then implement methods, as shown above.

In the main function, we can have instances for the Vehicle structs as shown:

fnmain() {
let car = Vehicle{
        model: "Camry".to_string(),
        manufacturer: "Toyota".to_string(),
        price: 25295
    };
let motorcycle = Vehicle {
        model: "V-Max".to_string(),
        manufacturer: "Yamaha".to_string(),
        price: 27999
    };
}

In the code above, we define two instances of the Vehicle struct with the properties implemented differently.

Calling Trait Methods

Once we have implemented the methods for a trait, we can call the method using the dot notation as shown:

println!("{}", car.description());

This should return:

Model: Camry, Manufacturer: Toyota, Price: 25295

Conclusion

This guide provides the fundamentals for working with traits in the Rust language. Consider the documentation to learn more.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list