Skip to content

[Question] Generic support for trait #947

@yamajik

Description

@yamajik

Any possible to introduce Rust From/Into into Moonbit?

Currently, I'm working on a native project, which needs to bind structs between Moonbit/Rust. Built-in From/Into traits in Rust are an elegant way for conversion, I am looking for the very same way in Moonbit. Here's my proposal.

enum Type {
  TypeA
  TypeB(Int)
  TypeC(field1~: Int, field2~: Int)
}

struct CTypeStruct {
  tag: TypeTag
  data: TypeData
}

enum TypeTag {
  TypeA = 0
  TypeB = 1
  TypeC = 2
}

struct TypeData {
  b: Option[TypeBData]
  c: Option[TypeCData]
}

struct TypeBData {
  val: Int
}

struct TypeCData {
  field1: Int
  field2: Int
}

impl From[CTypeStruct] for Type with from {
  fn from(value: CTypeStruct) -> Self {
    match value.tag {
      TypeTag::TypeA => Type::TypeA
      TypeTag::TypeB => Type::TypeB(value.data.b.unwrap().val)
      TypeTag::TypeC => {
        let { field1, field2 } = value.data.c.unwrap();
        Type::TypeC(field1=field1, field2=field2)
      }
    }
  }
}

impl From[Type] for CTypeStruct with from {
  fn from(value: Type) -> Self {
    match value {
      Type::TypeA => {
        tag: TypeTag::TypeA,
        data: TypeData::empty(),
      }
      Type::TypeB(val) => {
        tag: TypeTag::TypeB,
        data: { b: Some({ val }), c: None },
      },
      Type::TypeC { field1, field2 } => {
        tag: TypeTag::TypeC,
        data: { b: None, c: Some(TypeCData { field1, field2 }) },
      },
    }
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions