struct - 如何创建嵌套结构?

标签 struct rust

我正在实现一个具有嵌套结构调用的方法。 我阅读了有关 Rust 生命周期的信息,我认为我的问题与生命周期有关,但我无法理解如何在代码中使用它。

#[derive(Debug)]
pub struct Request {
    Header: String
} 
#[derive(Debug)]
pub enum Proto {
    HTTP,
    HTTPS
}

#[derive(Debug)]
pub struct HTTP {
    ssss: Request,
    names: Proto,
}

impl HTTP {
    pub fn new(name: Proto) -> HTTP {
        HTTP{
            ssss.Header: "Herman".to_string(),
            names: name,
        }
    }
}

不可能为 ssss.Header 赋值:

error: expected one of `,` or `}`, found `.`
  --> src/main.rs:20:17
   |
20 |             ssss.Header: "Herman".to_string(),
   |                 ^ expected one of `,` or `}` here

error[E0425]: cannot find value `ssss` in this scope
  --> src/main.rs:20:13
   |
20 |             ssss.Header: "Herman".to_string(),
   |             ^^^^
   |             |
   |             `self` value is only available in methods with `self` parameter
   |             help: try: `self.ssss`

error[E0063]: missing field `names` in initializer of `HTTP`
  --> src/main.rs:19:9
   |
19 |         HTTP{
   |         ^^^^ missing `names`

最佳答案

嵌套结构并没有什么神奇之处。您使用与非嵌套结构完全相同的语法:

pub fn new(name: Proto) -> HTTP {
    HTTP {
        ssss: Request {
            header: "Herman".to_string(),
        },
        names: name,
    }
}

如果你觉得嵌套太复杂,你总是可以引入一个中间变量:

pub fn new(names: Proto) -> HTTP {
    let ssss = Request {
        header: "Herman".to_string(),
    };

    HTTP { ssss, names }
}

注意:惯用的 Rust 使用 snake_case 作为变量、方法和结构属性等标识符。我已将您的 Header 重命名为 header 以避免警告。

关于struct - 如何创建嵌套结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48550453/

相关文章:

c++ - 为什么我不能成功读取文件数据到结构数组

inheritance - Golang : when typecasting child struct to parent struct, 子结构信息丢失?

methods - 在函数内部定义结构的方法

rust - (Rust) 有没有办法为重载的运算符自动借用?

rust - 如何收集到数组中?

go - 将匿名全局结构清零

c - C 中的结构和多维数组全局声明

error-handling - 无法将io::Error从可见结果中移出

rust - 如何在Rust中从标准中获取多个输入?

rust - 从闭包内部使用 continue 的 Rust 方法是什么?