Is there a function similar to trait in Rust

For example.

module A = {
  type t
  type getKind = t => string
}

module B = {
  type t
  type getKind = t => string
 }

module C = {
  type t
}

Now I want to implement a function that requires the parameters to implement getKind, so that it can only accept A and B, but not C.

How can I implement this in Rescript?

Your getKind example hinting at maybe something else but a “module type” is the first suggestion:

module type Kinded = {
  let getKind: t => string
}

module User = (K: Kinded) => {
  let caller = (t: K.t) => {
    K.getKind(t)
  }
}

HTH

3 Likes

It works, thank you very much.

Another approach would be to implement your “getKind” function in each module then pass one as your function parameter (as a first class module)

module type Kinded = {
  let getKind: unit => string
}

module A = {
  let getKind = () => "A"
}

module B = {
  let getKind = () => "B"
}

module C = {
   let notTheSame = () => "C"
}

let getKind = (~kind: module(Kinded)) => {
  let module(Kinded) = kind
  Kinded.getKind
}

getKind(~kind=module(A))->Js.log  // A
getKind(~kind=module(B))->Js.log  // B
getKind(~kind=module(C))->Js.log  // Type Errors. Signature mismatch: The value `getKind' is required but not provided
5 Likes

How do you choose first class module or functor?

I think you just have to choose the one that fit best your needs, that is easily maintainable and scalable.