如何从 Rust 中的字符串构建对象?

问题描述 投票:0回答:1

我正在 rust 中创建一个子例程,它将表示对象属性及其值的自定义数据类型转换为该对象,但我不知道该怎么做...

我这样做是因为我想从用户输入创建对象,我的计划是首先获取输入并将其解析为自定义数据类型,然后将该数据转换为对象。

我的问题是,当迭代自定义数据类型时,我得到了表示该属性的字符串,但我不知道如何检查该字符串是否是真实属性或如何将值分配给该属性。

这是我到目前为止所尝试过的,但现在我被困住了:

enum Value {
    String(String),
    Float(f64),
    Boolean(bool),
    Object(String, Vec<(String, Value)>),
} // Vec<(String, Value)>, E.g. ["Kind", Object("Particle", [("energy", 4.3), ("shape", Object("Sphere", [("radius", 3.2)]))])]


fn create_spell(properties: Vec<(String, Value)>) -> Spell {
    let mut spell = Spell::new();

    fn create_spell_inner(properties: Vec<(String, Value)>, spell: &mut Spell) {
        for property in properties{
            match property {
                // String = attribute name of current object
                // Value = attribtue value of current object
                
            }
        }
    }
    return spell;
}

Createpell 接受自定义数据类型并返回对象、Spell,或者至少这就是它的意图。

如果您想查看编写本文时的其余代码,请看这里,但它是一堆大多未使用的函数、结构和枚举:https://github.com/CocytusDEDI/MMSpellbook/blob/ 14a8b5ff31476b99cdec2ebbc28ec647367f2635/src/main.rs

oop rust type-conversion
1个回答
0
投票

您可以为您的自定义类型实现

FromStr
特征:docs。它已经针对 f64 等实现了。但是,如果 serde 适合您的目的,这可能会不必要地耗时(归功于 @vallentin)。

另一个注意事项:你声明了

create_spell_inner
但从未调用它。您可能应该将
for
循环放入
create_spell
的主体中。

© www.soinside.com 2019 - 2024. All rights reserved.