Sivakumar
Posted on January 21, 2023
In this blog post, let us see how to work with Traits
in Rust
Traits
Traits is equivalent to Interfaces in Java. Traits can be made up of three varieties of associated items such as:
- Functions and Methods
- Constants
- Types
When a type implements a trait it can be treated abstractly as that trait using generics or trait objects.
Create Traits
Traits can be created by using trait keyword.
trait TypeUtils {
fn is_in_range(&self) -> bool;
}
Implement Traits for a type
It is possible to implement traits for a specific type (primitive or custom types)
In this below example, we can see how to implement TypeUtils trait for some of standard library types
impl TypeUtils for String {
fn is_in_range(&self) -> bool {
false
}
}
impl TypeUtils for i32 {
fn is_in_range(&self) -> bool {
true
}
}
impl TypeUtils for str {
fn is_in_range(&self) -> bool {
true
}
}
It is also possible to implement Trait for custom types such as Structs. In this below example, we're creating an Employee Struct and implementing TypeUtils trait
struct Employee {
name: String,
age: i32,
}
impl TypeUtils for Employee {
fn is_in_range(&self) -> bool {
true
}
}
Call traits methods implemented for a type
After declaring Traits and implementing them for type, let us see how to call the trait methods
fn main() {
let s: String = String::from("Rust");
let i: i32 = 100;
let s1: &str = "Rust is awesome";
let e: Employee = Employee::new(String::from("John"), 30);
println!("Is '{s}' within range?: {}", s.is_in_range());
println!("Is '{i}' within range?: {}", i.is_in_range());
println!("Is '{s1}' within range?: {}", s1.is_in_range());
println!("Is {e:#?} within range?: {}", e.is_in_range());
}
I hope this blog post gives you a brief overview about Traits.
All the code examples can be found in this link.
Please feel free to share your feedback.
Happy reading!!!
Posted on January 21, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.