Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 895
Greg Avatar asked Nov 07 '17 13:11

Greg


People also ask

Are structs passed by value in C?

In C, all arguments are passed to functions by value, including structs. For small structs, this is a good thing as it means there is no overhead from accessing the data through a pointer.

Can a struct contain an object?

A variable of a struct type directly contains the data of the struct , whereas a variable of a class type contains a reference to the data, the latter known as an object. As described in §8.3. 5, the simple types provided by C#, such as int , double , and bool , are, in fact, all struct types.

Does rust have structs?

Structs in Rust come in three flavors: Structs with named fields, tuple structs, and unit structs. Regular structs are the most commonly used. Each field defined within them has a name and a type, and once defined can be accessed using example_struct. field syntax.


1 Answers

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.

like image 197
Shepmaster Avatar answered Oct 11 '22 11:10

Shepmaster