8

I want to create a function (for a library) which will output a struct for any CSV which contains all the columns and their data. This means that the column names (unless explicitly provided by the user) will not be known until runtime.

Is it possible to create a struct definition at runtime or mutate an existing struct? If so, how?

For example, how can I mutate the following struct structure:

struct Point {
    x: String,
    y: String,
}

To the following (in memory only):

struct Point {
    x: String,
    y: String,
    z: String,
}

This behaviour is possible in languages such as Python, but I am not sure if it is possible in compiled languages such as Rust.

Shepmaster
  • 274,917
  • 47
  • 731
  • 969
Greg
  • 6,043
  • 8
  • 41
  • 93
  • 3
    You want a HashMap : https://doc.rust-lang.org/std/collections/struct.HashMap.html – Grégory OBANOS Nov 07 '17 at 13:44
  • 4
    I could have sworn someone asked this question before, but I couldn't find it. You may find [How does Rust implement reflection](https://stackoverflow.com/q/36416773/3650362) and [Using reflection to enumerate through the fields of a struct at runtime](https://stackoverflow.com/q/30407009/3650362) interesting, though. – trentcl Nov 07 '17 at 13:51
  • 1
    I also found [Is it possible to generate and execute Rust code at runtime?](https://stackoverflow.com/q/14459647/155423), which isn't quite the same question either. – Shepmaster Nov 07 '17 at 14:29

1 Answers1

10

No, it is not possible.

Simplified, at compile time, the layout (ordering, offset, padding, etc.) of every struct is computed, allowing the size of the struct to be known. When the code is generated, all of this high-level information is thrown away and the machine code knows to jump X bytes in to access field foo.

None of this machinery to convert source code to machine code is present in a Rust executable. If it was, every Rust executable would probably gain several hundred megabytes (the current Rust toolchain weighs in at 300+MB).

Other languages work around this by having a runtime or interpreter that is shared. You cannot take a Python source file and run it without first installing a shared Python interpreter, for example.

Additionally, Rust is a statically typed language. When you have a value, you know exactly what fields and methods are available. There is no way to do this with dynamically-generated structs — there's no way to tell if a field/method actually exists when you write the code that attempts to use it.


As pointed out in the comments, dynamic data needs a dynamic data structure, such as a HashMap.

Shepmaster
  • 274,917
  • 47
  • 731
  • 969