繁体   English   中英

遍历 rust 中的结构

[英]Iterate over struct in rust

我对来自 JS/TS 的 Rust 完全陌生

我已经看到其他问题,例如: How do I iterate over a elements of a struct in Rust? 但他们没有让我得到真正的答案。

我正在尝试迭代 rust 中结构的键和值

在 JS/TS 中,这将像这样工作:

const o = {
    a: "hello",
    b: "world"
};

const keys = Object.keys(o);
const values = Object.values(o);

// now loop over them 

这样的东西在 Rust 中如何工作?

我正在使用 Serde 将配置 yaml 文件解析为结构。


#[derive(Deserialize, Debug, Clone)]
pub struct Config {
    pub headers: Headers,
}

#[derive(Deserialize, Debug, Clone)]
pub struct Headers {
    #[serde(rename = "Content-Security-Policy")]
    pub content_security_policy: String,
    #[serde(rename = "x-frame-options")]
    pub x_frame_options: String,
    #[serde(rename = "x-content-type-options")]
    pub x_content_type_options: String,
    #[serde(rename = "x-permitted-cross-domain-policies")]
    pub x_permitted_cross_domain_policies: String,
    #[serde(rename = "x-download-options")]
    pub x_download_options: String,
    #[serde(rename = "x-xss-protection")]
    pub x_xss_protection: String,
    #[serde(rename = "referrer-policy")]
    pub referrer_policy: String,
    #[serde(rename = "Strict-Transport-Security")]
    pub strict_transport_security: String,
    #[serde(rename = "feature-policy")]
    pub feature_policy: String,
    #[serde(rename = "Cache-Control")]
    pub cache_control: String,
}

但这并没有实现.iter() function 并且我还没有找到搜索这个的解决方案。

感谢凯撒

我试过这个:


use serde::{Deserialize, Serialize};

#[derive(Deserialize, Debug, Clone, Serialize)]
pub struct Config {
    pub headers: Headers,
}

#[derive(Deserialize, Debug, Clone, Serialize)]
pub struct Headers {
    #[serde(rename = "Content-Security-Policy")]
    pub content_security_policy: String,
    #[serde(rename = "x-frame-options")]
    pub x_frame_options: String,
    #[serde(rename = "x-content-type-options")]
    pub x_content_type_options: String,
    #[serde(rename = "x-permitted-cross-domain-policies")]
    pub x_permitted_cross_domain_policies: String,
    #[serde(rename = "x-download-options")]
    pub x_download_options: String,
    #[serde(rename = "x-xss-protection")]
    pub x_xss_protection: String,
    #[serde(rename = "referrer-policy")]
    pub referrer_policy: String,
    #[serde(rename = "Strict-Transport-Security")]
    pub strict_transport_security: String,
    #[serde(rename = "feature-policy")]
    pub feature_policy: String,
    #[serde(rename = "Cache-Control")]
    pub cache_control: String,
}

let iterable_headers: HashMap<String, String> =
 serde_yaml::from_value(serde_yaml::to_value(&config.headers).unwrap()).unwrap();

for header in &iterable_headers {
    res = res.header(header.0, header.1);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM