Tuple struct constructor complains about private fields

巧了我就是萌 提交于 2019-11-30 08:02:34

问题


I am working on a basic shell interpreter to familiarize myself with Rust. While working on the table for storing suspended jobs in the shell, I have gotten stuck at the following compiler error message:

error: cannot invoke tuple struct constructor with private fields [E0450]
     let jobs = job::JobsList(vec![]);
                ^~~~~~~~~~~~~

It's unclear to me what is being seen as private here. As you can see below, both of the structs are tagged with pub in my module file. So, what's the secret sauce?

mod job {
    use std::fmt;

    pub struct Job {
        jid: isize,
        pid: isize,
        cmd: String,
    }

    pub struct JobsList(Vec<Job>);
}

fn main() {
    let jobs = job::JobsList(vec![]);
}

回答1:


As the error message suggests, the problem is JobsList has a private field, that is, the Vec<Job> value is inaccessible outside the module that defines the struct. This means that you cannot pattern match on a JobsList value to extract it, and that you cannot construct it directly.

There's two fixes:

  • make the field public pub struct JobsList(pub Vec<Job>);
  • provide a public constructor

    impl JobsList {
        pub fn new(jobs: Vec<Job>) -> JobsList {
            JobsList(jobs)
        }
    }
    

    called like JobsList::new(vec![]).



来源:https://stackoverflow.com/questions/24110970/tuple-struct-constructor-complains-about-private-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!