1

I am working on a project relying on starknet-rs which defines a lot of types (enum and structs) that we want to reuse.

However, it's not straightforward to implement a trait on an external type (Why does Rust prevent implementing an external trait for an external struct?)

So currently, we end up having things like

enum OpcodeWrapper {
    NOp,
    AssertEq,
    Call,
    Ret,
}

impl From<Opcode> for OpcodeWrapper {
    fn from(value: Opcode) -> Self {
        match value {
            Opcode::AssertEq => Self::AssertEq,
            Opcode::Call => Self::Call,
            Opcode::NOp => Self::NOp,
            Opcode::Ret => Self::Ret,
        }
    }
}
impl From<OpcodeWrapper> for Opcode {
    fn from(value: OpcodeWrapper) -> Self {
        match value {
            OpcodeWrapper::AssertEq => Self::AssertEq,
            OpcodeWrapper::Call => Self::Call,
            OpcodeWrapper::NOp => Self::NOp,
            OpcodeWrapper::Ret => Self::Ret,
        }
    }
}

so that we can do whatever we want with the Wrapper type. Is there any way to avoid this sort of copy/pasta? And since the two types are not the "same", all the subsequent .into()?

ClementWalter
  • 4,814
  • 1
  • 32
  • 54
  • I have linked this question in my question actually. I am not asking "why" but "how" to circumvent this for the reason explained: "fake" different types, copy/paste and burden of `into` for exemple. What is the current best practice when facing this? – ClementWalter May 22 '23 at 10:58
  • Ah yes, sorry that wasn't the correct Q/A, fortunately it's now linked. – cafce25 May 22 '23 at 11:02
  • 1
    As per [this answer](https://stackoverflow.com/a/74372037), create a newtype around the imported type, which you can now implement whichever traits for. – E_net4 May 22 '23 at 11:03

0 Answers0