问题描述
在,它们表明 pub枚举
无法容纳私有的 struct
: ,
In Learning Rust With Entirely Too Many Linked Lists, they show that a pub enum
can't hold a private struct
:,
struct Node {
elem: i32,
next: List,
}
pub enum List {
Empty,
More(Box<Node>),
}
这将导致编译器抱怨:
error[E0446]: private type `Node` in public interface
--> src/main.rs:8:10
|
8 | More(Box<Node>),
| ^^^^^^^^^^ can't leak private type
但是此代码不会即使 Link
是私有的,也会导致错误:
But this code will not cause an error even though Link
is private:
pub struct List {
head: Link,
}
enum Link {
Empty,
More(Box<Node>),
}
struct Node {
elem: i32,
next: Link,
}
此差异的原因是什么?为什么私有枚举不会在私有结构引起错误的呢?
What is the reason for this discrepancy? Why does a private enum not cause an error while a private struct does?
推荐答案
在第一个示例中,枚举列表
是公开的。这意味着枚举变体 More
也是公开的。但是,更多
不能被外部代码使用,因为 Node
不是公开的。因此,您所拥有的东西在外部是可见的,但实际上并不能被使用,这可能不是您想要的。
In the first example, the enum List
is public. That means that the enum variant More
is also public. However, More
cannot be used by external code because Node
isn't public. Thus, you have a thing that is externally visible, but can't actually be used, which is probably not what you wanted.
在第二个示例,结构 List
是公共的。但是, head
字段是不公开的。因此, Link
是否公开并不重要,因为外部代码看不到 head
字段首先。
In the second example, the struct List
is public. However, the head
field is not public. Thus, it doesn't matter whether Link
is public or not, because external code can't see the head
field in the first place.
这篇关于为什么“不能泄漏私有类型”?仅适用于结构而不适用于枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!