Why does “can't leak private type” only apply to structs and not enums?

╄→гoц情女王★ 提交于 2020-05-22 08:03:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!