是否可以在运行时定义结构或以其他方式实现类似的效果? [英] Is it possible to define structs at runtime or otherwise achieve a similar effect?

查看:48
本文介绍了是否可以在运行时定义结构或以其他方式实现类似的效果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数(用于库),它将为包含所有列及其数据的任何 CSV 输出一个结构.这意味着直到运行时才会知道列名(除非用户明确提供).

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,
}

以下(仅在内存中):

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

这种行为在 Python 等语言中是可能的,但我不确定在 Rust 等编译语言中是否可能.

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

推荐答案

不,这是不可能的.

简化,在编译时,计算每个结构的布局(排序、偏移、填充等),从而知道结构的大小.当代码生成时,所有这些高级信息都被丢弃了,机器代码知道要跳转 X 个字节来访问字段 foo.

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.

在 Rust 可执行文件中不存在将源代码转换为机器代码的任何机制.如果是这样,每个 Rust 可执行文件可能会增加数百兆字节(当前的 Rust 工具链重量为 300+MB).

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).

其他语言通过共享运行时或解释器来解决此问题.例如,如果不先安装共享的 Python 解释器,就无法获取 Python 源文件并运行它.

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.

此外,Rust 是一种静态类型语言.当您有一个值时,您就确切地知道哪些字段和方法可用.动态生成的结构无法做到这一点——当您编写尝试使用它的代码时,无法判断字段/方法是否确实存在.

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.

正如评论中所指出的,动态数据需要一个动态的数据结构,例如HashMap.

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

这篇关于是否可以在运行时定义结构或以其他方式实现类似的效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆