Skip to content

Commit 0dc3179

Browse files
committed
code for 0x0c Operarot overloading
1 parent 9f25491 commit 0dc3179

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
use std::fmt;
2+
use std::fmt::Write;
3+
use std::ops;
4+
5+
#[derive(Debug, Clone)]
6+
struct MyString(String);
7+
8+
impl fmt::Display for MyString {
9+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10+
write!(f, "{}", self.0)
11+
}
12+
}
13+
14+
impl ops::Add<String> for MyString {
15+
type Output = MyString;
16+
17+
fn add(self, rhs: String) -> Self::Output {
18+
println!("> MyString.add({}) was called", &rhs);
19+
MyString(format!("{}{}", self.0, rhs))
20+
}
21+
}
22+
23+
impl ops::Add<i32> for MyString {
24+
type Output = MyString;
25+
26+
fn add(self, rhs: i32) -> Self::Output {
27+
println!("> MyString.add({}) was called", &rhs);
28+
MyString(format!("{}{}", self.0, rhs))
29+
}
30+
}
31+
32+
impl ops::Add<MyString> for i32 {
33+
type Output = MyString;
34+
35+
fn add(self, rhs: MyString) -> Self::Output {
36+
println!("> i32.add({}) was called", &rhs);
37+
MyString(format!("{}{}", self, rhs))
38+
}
39+
}
40+
41+
impl ops::Mul<i32> for MyString {
42+
type Output = MyString;
43+
44+
fn mul(self, rhs: i32) -> Self::Output {
45+
println!("> MyString.mul({}) was called", &rhs);
46+
let caplen: usize = if rhs <= 0 { 0 } else { rhs as usize };
47+
let mut temp = String::with_capacity(&self.0.len() * caplen);
48+
for _ in 0..rhs {
49+
temp.write_str(&self.0).expect("writing to string failed");
50+
}
51+
MyString(temp)
52+
}
53+
}
54+
55+
fn main() {
56+
let ms = MyString("Foo".to_string());
57+
println!("Foo + Bar = {}", ms + "Bar".to_string());
58+
println!("Foo + -12 = {}", ms + -12_i32);
59+
println!("100 + Foo = {}", 100_i32 + ms.clone());
60+
println!("Foo * -12 = {}", ms.clone() * -12_i32);
61+
println!("Foo * 12 = {}", ms.clone() * 12_i32);
62+
}

0 commit comments

Comments
 (0)