Is it possible to define structs at runtime or otherwise achieve a similar effect?

风格不统一 提交于 2021-02-04 22:17:27

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/47159418/is-it-possible-to-define-structs-at-runtime-or-otherwise-achieve-a-similar-effec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!