2

I'm not much into Rust and I look into it when I need to check whether it's possible to do some interesting things using its type system. And I've come up with a question if it's possible to convert the following type definitions written in TS to Rust.

type Data = {
    path: String
    name: String
}

enum Type {
    CSV,
    JPG,
    PNG
}

type CSV = Data & {
    type: Type.CSV
}

type JPG = Data & {
    type: Type.PNG
}

type PNG = Data & {
    type: Type.PNG
}

// To avoid conflicts with the already reserved type File
type MyFile = CSV | PNG | JPG

I've been trying to google something like if it's possible to extend structs in Rust and unfortunately didn't find anything answering my curiosity.

E_net4
  • 27,810
  • 13
  • 101
  • 139

1 Answers1

2

No, it is not possible to extend a struct in Rust.

Trying to do a direct conversion between this Typescript sample and the equivalent Rust wouldn't be idiomatic anyway. You'd probably want to structure it either like this:

enum Kind {
    Csv,
    Jpg,
    Png,
}

struct MyFile {
    kind: Kind,
    path: String,
    name: String,
}

or like this:

struct Data {
    path: String,
    name: String,
}

enum MyFile {
    Csv(Data),
    Jpg(Data),
    Png(Data),
}

depending on your coupling of path/name to the file type.

kmdreko
  • 42,554
  • 6
  • 57
  • 106
  • Thank you very much! The idea behind my types is to implement a function, that accepts only CSV or PNG files depending on the context. For example, imagine that I wanna have a function/type that works with only a specific type. For example, I have a user whose avatar should be only PNGs, so going the first way can't guarantee that. I don't really understand yet how the second example works, and I would really appreciate it if you could share some info for me to dive into that. – Rostislav Zhuravsky Nov 09 '22 at 17:58
  • For that, you'd need different types for each enum variant (i.e. `CsvData`, etc) [like this](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0c05acc70d4bc7b5ec55a3a61a894856). Or if you want to reduce duplication of those fields (in case there are more), you'd use composition [like this](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=b973cabf399b4abb875685cb17d09600). – kmdreko Nov 09 '22 at 18:23