元组结构构造函数抱怨私有字段 [英] Tuple struct constructor complains about private fields

查看:108
本文介绍了元组结构构造函数抱怨私有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个基本的 shell 解释器来熟悉 Rust.在处理用于在 shell 中存储挂起作业的表时,我遇到了以下编译器错误消息:

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![]);
                ^~~~~~~~~~~~~

我不清楚什么在这里被视为私人的.正如您在下面看到的,这两个结构在我的模块文件中都带有 pub 标记.那么,秘诀是什么?

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![]);
}

推荐答案

如错误提示所示,问题是JobsList有一个私有字段,即Vec 值在定义 struct 的模块之外是不可访问的.这意味着您不能对 JobsList 值进行模式匹配来提取它,也不能直接构造它.

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.

有两个修复:

  • 将字段设为公开 pub struct JobsList(pub Vec);
  • 提供一个公共构造函数

  • 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)
    }
}

JobsList::new(vec![])一样调用.

这篇关于元组结构构造函数抱怨私有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆