<예제 코드_1>
use std::ops;
struct Foo;
struct Bar;
#[derive(Debug)]
struct FooBar;
#[derive(Debug)]
struct BarFoo;
// The 'std::ops::Add' trait is used to specify the functionality of '+'.
// Here, we make 'Add<Bar>' - the trait for addition with a RHS of type 'Bar'.
// The follow block implements the operation: Foo + bar = FooBar
impl ops::Add<Bar> for Foo {
type Output = FooBar;
fn add(self, _rhs: Bar) -> FooBar {
println!("> Foo.add(Bar) was called");
FooBar
}
}
// By reversing the types, we end up implementing non-commutative addition.
// Here, we make 'Add<Foo>' - the trait for addition with a RHS of type 'Foo'.
impl ops::Add<Foo> for Bar {
type Output = BarFoo;
fn add(self, _rhs: Foo) -> BarFoo {
println!("> Bar.add(Foo) was called");
BarFoo
}
}
fn main() {
println!("Foo + Bar = {:?}", Foo + Bar);
println!("Bar + Foo = {:?}", Bar + Foo);
}
<참조 1> https://doc.rust-lang.org/rust-by-example/trait/ops.html
<참조 2>
'Rust' 카테고리의 다른 글
[Rust] Tokio 예제 : 기본 (53일차) (0) | 2023.02.05 |
---|---|
[Rust] HashMap 예제 (52일차) (0) | 2023.02.03 |
[Rust] Field Init Shorthand, 필드 초기화 (50일차) (0) | 2023.02.01 |
[Rust] Web Server : Multi-Threading 추가 (49일차) (0) | 2023.01.31 |
댓글