Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

rust - Tuple struct constructor complains about private fields

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![]);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 are 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![]).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...