【发布时间】:2017-12-18 14:07:22
【问题描述】:
我经常使用newtype模式,但是写my_type.0.call_to_whatever(...)很累。我很想实现Deref trait,因为它允许编写更简单的代码,因为我可以在某些情况下使用我的 newtype,就好像它是底层类型一样,例如:
use std::ops::Deref;
type Underlying = [i32; 256];
struct MyArray(Underlying);
impl Deref for MyArray {
type Target = Underlying;
fn deref(&self) -> &Self::Target {
&self.0
}
}
fn main() {
let my_array = MyArray([0; 256]);
println!("{}", my_array[0]); // I can use my_array just like a regular array
}
这是一个好习惯还是坏习惯?为什么?有什么缺点?
【问题讨论】:
标签: rust dereference