元组结构构造函数抱怨私有字段 [英] Tuple struct constructor complains about private fields
问题描述
我正在开发一个基本的 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屋!