gpt4 book ai didi

rust - 如何动态访问结构属性?

转载 作者:行者123 更新时间:2023-12-03 11:41:01 25 4
gpt4 key购买 nike

我是Rust的初学者,想知道如何动态访问struct的字段:

use std::collections::HashMap;

struct User {
email: String,
name: String,
}

impl User {
fn new(attributes: &HashMap<String,String>) -> User {
let mut model = User {
email: "",
name: "",
};

for (attr_name,attr_value) in attributes {
// assign value "attr_value" to attribute "attr_name"
// no glue how to do this
// in php would be: $model->{$attr_name} = $attr_value;
model.*attr_name *= attr_value;
}

model;
}
}

fn main() {

let mut map: HashMap::new();
map.insert("email",String::from("foo@bar.de"));
map.insert("name",String::from("John doe"));

user_model = User::new(&map);

println!("{:?}",user_model);
}
如何通过给定的 struct初始化 HashMap

最佳答案

除非您将User更改为包含HashMap,否则Rust无法做到这种“魔术”效果(否则它将需要一些proc宏用法,这对初学者而言不是很友好)。
相反,您可以使用match,并匹配所有键并更新User字段:

for (attr_name, attr_value) in attributes {
match attr_name {
"email" => model.email = attr_value.clone(),
"name" => model.name = attr_value.clone(),
_ => {}
}
}
但是,建议不要使用 String为空,而建议使用 Option<String>
struct User {
email: Option<String>,
name: Option<String>,
}
然后,您可以将整个 new方法简化为:
fn new(attributes: &HashMap<String, String>) -> User {
User {
email: attributes.get("email").cloned(),
name: attributes.get("name").cloned(),
}
}

由于您混合使用了 String&'static str,因此未实现 Debug。然后是完整的示例:
use std::collections::HashMap;

#[derive(Debug)]
struct User {
email: Option<String>,
name: Option<String>,
}

impl User {
fn new(attributes: &HashMap<String, String>) -> User {
User {
email: attributes.get("email").cloned(),
name: attributes.get("name").cloned(),
}
}
}

fn main() {
let mut map = HashMap::new();
map.insert(String::from("email"), String::from("foo@bar.de"));
map.insert(String::from("name"), String::from("John doe"));

let user_model = User::new(&map);

println!("{:?}", user_model);
}

关于rust - 如何动态访问结构属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65169079/

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