Deref型
Deref型
代表的なDeref型
- 参照型
&T
- スマートポインタ
String
,Box<T>
, ...
3つのDeref型強制
If T implements Deref<Target = U>
, and x is a value of type T
, then:
- In immutable contexts,
*x
(where T is neither a reference nor a raw pointer) is equivalent to*Deref::deref(&x)
. - Values of type
&T
are coerced to values of type&U
T
implicitly implements all the (immutable) methods of the typeU
.
1. Dereference(*
)演算子によるDeref型強制
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] struct Foo(i32);
let foo1 = Foo(1); let foo2 = &Foo(2); // *演算子でFoo型に戻すことができる if foo1 > *foo2 {}
2. 型宣言とBorrow(&
)演算子によるDeref型強制
型宣言 することで、参照型(&U
)として取り出すことができる。
一種のキャスト?にあたるかも。
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] struct Foo(i32); struct FooBox(Foo); impl Deref for FooBox { type Target = Foo; fn deref(&self) -> &Self::Target { &self.data } }
let foo = Foo(5); let foo_box = FooBox(foo); let foo2: &Foo = &foo_box; // &演算子によるDeref型強制
3. ドット(.
)演算子によるDeref型強制
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] struct Foo(i32); impl Foo { fn say_hello(&self) { println!("Hello Everyone") } } struct FooBox(Foo); impl Deref for FooBox { type Target = Foo; fn deref(&self) -> &Self::Target { &self.data } }
let foo = Foo(5); let foo_box = FooBox {data: foo}; foo_box.say_hello(); // 自動参照外しによるDeref型強制