Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 458
Jal Avatar asked Oct 11 '17 04:10

Jal


Video Answer


1 Answers

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.

like image 134
DK. Avatar answered Sep 17 '22 10:09

DK.