gpt4 book ai didi

rust - serde如何将字符串中的值转换为类型

转载 作者:行者123 更新时间:2023-11-29 08:08:33 25 4
gpt4 key购买 nike

我已经构建了一个 ECS(我认为是一个简单的)并且我已经构建了一种机制来将外部数据(实体模板)加载到我的程序中我遇到的问题是如何将已经加载的数据转换为类型。

Serde我想查看如何执行此操作,但我实际上找不到执行此操作的部件。

我的意思是,当您创建这样的数据结构时:

person:
name: Bob
age: 34

并且 serde 能够将其转换为结构:

struct Person {
name: String,
age: i32
}

serde如何将字符串person转换为Person类型

编辑:用另一种语言(ruby)举个例子:

class Person
attr_accessor :name, :age
def initialize(name:, age:)
@name = name
@age = age
end
end

# pretend type was loaded in from the yaml example from the key
type = 'person'

# pretend person_data was loaded in from the yaml example form the value of the key
person_data = {
name: 'Bob',
age: 34
}

# and now we get the type and then initialize it
# Just like serde does
const_get(type.capitalize).new(person_data)

现在显然 Rust 不能在运行时这样做或这样做,但 serde 必须做一些事情以得到相同的结果,"person" 转换为 Person.

最佳答案

你告诉 serde 你想要的类型。它从 Derive 实现中知道成员的类型。

关于rust - serde如何将字符串中的值转换为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52900274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com