-
Notifications
You must be signed in to change notification settings - Fork 2
/
extension_method.rs
53 lines (45 loc) · 1.29 KB
/
extension_method.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
Once we implement an extension trait over a specific type [String,Integer,Bool...] we can start using
this new method like part of this API.
*/
pub fn run() {
println!("Contains hello:{}","Hello world".contains_hello());
println!("Number:{}",1981.multiply_by(10));
println!("Animal info:{}",Animal{ species:"Dog".to_string(), age:5}.animal_description());
}
/**
Make extension methods in Rust is quite simple and clean.
We just need to define a [trait] with the the definition we want to extend.
And then create an implementation [impl] using the specific type to extend after [for]
*/
trait StringExt {
fn contains_hello(&self) -> bool;
}
/**Implementation extension of [str] type*/
impl StringExt for str {
fn contains_hello(&self) -> bool {
self.contains("Hello")
}
}
trait NumberExt {
fn multiply_by(&self,number:i32) -> i32;
}
/**Implementation extension of [i32] type*/
impl NumberExt for i32 {
fn multiply_by(&self, number: i32) -> i32 {
self * number
}
}
trait AnimalExt {
fn animal_description(self)->String;
}
/**Implementation extension of [Animal] type*/
impl AnimalExt for Animal{
fn animal_description(self) -> String {
self.species + &"-" + &self.age.to_string()
}
}
struct Animal {
species:String,
age:i32,
}