Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to extend a struct in Rust? [duplicate]

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.

like image 379
Rostislav Zhuravsky Avatar asked Oct 21 '25 11:10

Rostislav Zhuravsky


1 Answers

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.

like image 134
kmdreko Avatar answered Oct 23 '25 00:10

kmdreko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!