【问题标题】:missing struct fields error while creating an instance of struct创建结构实例时缺少结构字段错误
【发布时间】:2022-12-03 12:54:06
【问题描述】:

我想通过仅初始化某些字段来调用给定结构的 new 成员函数来创建结构。我收到错误 error[E0063]: missing fields b and join_handle in initializer of B::B。这是我的示例代码

主要.rs

mod B;
mod A;

fn main() {
    println!("Hello, world!");
}

A.rs

pub struct AS {
    a: String
}

B.rs

use crate::A::AS;
use std::thread;

pub struct B {
    a: String,
    b: AS,
    join_handle: thread::JoinHandle<()>
}

impl B {
    fn new() -> B {
        B {
            a: String::from("Hi"),
        }
    }
}

如何部分初始化结构?

【问题讨论】:

  • Rust 没有结构的部分初始化。

标签: rust


【解决方案1】:

你不知道。你不能在 Rust 中部分初始化任何东西。

也许您需要将某些字段设为可选。

【讨论】:

  • 我想在稍后阶段初始化剩余的字段,假设 join_handle 成员通过调用方法 start 产生一个线程
【解决方案2】:

您不能部分初始化结构。 您可以在 B 中使用 Options:

struct B {
    a: String,
    b: Option<AS>,
    join_handle: Option<thread::JoinHandle<()>>,
}
impl B {
    fn new() -> Self {
        Self {
            a: String::from("hi"),
            b: None,
            join_handle: None,
        }
    }
}

或者改用构建器:

use std::thread;
fn main() {
    println!("Hello, world!");
}

pub struct AS {
    a: String
}

pub struct B {
    a: String,
    b: AS,
    join_handle: thread::JoinHandle<()>
}

impl B {
    fn builder() -> BBuilder {
        BBuilder {
            a: String::from("Hi"),
            b: None,
            join_handle: None,
        }
    }
}

struct BBuilder {
    a: String,
    b: Option<AS>,
    join_handle: Option<thread::JoinHandle<()>>,
}

impl BBuilder {
    fn a(mut self, b: AS) -> Self {
        self.b = Some(b);
        self
    }
    fn join_handle(mut self, join_handle: thread::JoinHandle<()>) -> Self {
        self.join_handle = Some(join_handle);
        self
    }
    fn build(self) -> Option<B> {
        let Self{ a, b, join_handle } = self;
        let b = b?;
        let join_handle = join_handle?;
        Some(B { a, b, join_handle })
    }
}

【讨论】:

    猜你喜欢
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    相关资源
    最近更新 更多