Issue
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.
Solution
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.
Answered By - kmdreko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.