相关疑难解决方法(0)

为newtypes实现Deref被认为是一种不好的做法吗?

我经常使用newtype模式,但我厌倦了写作my_type.0.call_to_whatever(...).我很想实现这个Deref特性,因为它允许编写更简单的代码,因为我可以使用我的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
}
Run Code Online (Sandbox Code Playgroud)

这是一种好的还是坏的做法?为什么?可能是什么缺点?

dereference rust

24
推荐指数
2
解决办法
2542
查看次数

标签 统计

dereference ×1

rust ×1