Traits
A trait is similar to an interface in other programming languages.
It defines a set of methods that a type must implement, allowing you to specify what functionality a type provides without dictating how it provides it.
Implementing a trait on a type is similar to implementing regular methods.
The difference is that after
impl, we put the trait name we want to implement, then use theforkeyword, and then specify the name of the type we want to implement the trait for.Traits can provide default method implementations that types can override.
The
impl Traitsyntax works for straightforward cases but is actually syntax sugar for a longer form known as a trait bound.We can also specify more than one trait bound using
+syntax.References:
traits1.rs
// The trait `AppendBar` has only one function which appends "Bar" to any object
// implementing this trait.
trait AppendBar {
fn append_bar(self) -> Self;
}
impl AppendBar for String {
// Implement `AppendBar` for the type `String`.
fn append_bar(self) -> Self {
self + "Bar"
}
}
fn main() {
let s = String::from("Foo");
let s = s.append_bar();
println!("s: {s}");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn is_foo_bar() {
assert_eq!(String::from("Foo").append_bar(), "FooBar");
}
#[test]
fn is_bar_bar() {
assert_eq!(String::from("").append_bar().append_bar(), "BarBar");
}
}This exercise is easy we just need to implement trait item/function
append_barinside theimpl AppendBar for Stringblock.
traits2.rs
This exercise also similar like the first one.
We need to create implementation of
AppendBartrait forVec<String>Because we want to mutate the vector (
self) we need to addmutsyntax.The full implementation will look like this:
traits3.rs
In this exercise we need to create default implementation of
licensing_infothat will return"Default license".This default implementation will be called if not the trait is not implemented for the specified type.
traits4.rs
In this exercise we need to change the function signature of
compare_license_typesto accept bothSomeSoftwareandOtherSoftwaretype.We can do this using generics.
Or we can also use
impl Traitsyntax like this:You can read more about it in here: https://doc.rust-lang.org/book/ch10-02-traits.html#trait-bound-syntax
traits5.rs
In this exercise we need to update function signature of
some_functo accept implementation ofSomeTraitandOtherTrait.It means that given type must implement both trait.
We can do this by using
+syntax like this:
Last updated