问题
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>),
}
This will cause the compiler to complain:
error[E0446]: private type `Node` in public interface
--> src/main.rs:8:10
|
8 | More(Box<Node>),
| ^^^^^^^^^^ can't leak private type
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?
回答1:
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.
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.
来源:https://stackoverflow.com/questions/46680064/why-does-cant-leak-private-type-only-apply-to-structs-and-not-enums