为枚举实现 Deref 以获得其判别式?

问题描述 投票:0回答:1

Deref
文档具有以下示例代码作为如何使用
Deref
的示例,但存在一些无关紧要的差异:

struct X(u8);

impl std::ops::Deref for X {
    type Target = u8;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

它通过封装底层值并实现附加功能来实现简单的智能指针

我想使用这个,但我的值是范围受限的,即我需要比 0-255 更严格的范围内的值,因此考虑使用枚举来限制范围并通过其判别式获取值。这可行,但我无法再为其实现 Deref 行为:

enum Y { A, B, C, D, E, F, G, H }

impl std::ops::Deref for Y {
    type Target = u8;
    fn deref(&self) -> &Self::Target {
        &(self as u8) // errors
    }
}

有没有办法为枚举实现这种行为?

rust enums
1个回答
0
投票

这里有一个黑客。

如果你非常想要你的

Deref<Target=u8>
界面,你可以使用它。

#[derive(Copy, Clone)]
enum Y {
    A,
    B,
    C,
    D,
    E,
    F,
    G,
    H,
}

impl std::ops::Deref for Y {
    type Target = u8;
    fn deref(&self) -> &Self::Target {
        [&0, &1, &2, &3, &4, &5, &6, &9][*self as usize]
    }
}

fn main() {
    assert_eq!(dbg!(1 + *Y::B), 2);
}
© www.soinside.com 2019 - 2024. All rights reserved.