为什么 "can't leak private type" 只适用于结构而不适用于枚举?
Why does "can't leak private type" only apply to structs and not enums?
在 Learning Rust With Entirely Too Many Linked Lists 中,它们表明 pub enum
不能容纳私有 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
是私有的,这段代码也不会导致错误:
pub struct List {
head: Link,
}
enum Link {
Empty,
More(Box<Node>),
}
struct Node {
elem: i32,
next: Link,
}
造成这种差异的原因是什么?为什么私有枚举不会导致错误而私有结构会导致错误?
在第一个例子中,枚举 List
是 public。这意味着枚举变体 More
也是 public。但是,More
不能被外部代码使用,因为 Node
不是 public。因此,你有一个外部可见的东西,但实际上不能使用,这可能不是你想要的。
在第二个例子中,结构List
是public。但是,head
字段是 而不是 public。因此,Link
是否为 public 并不重要,因为外部代码首先看不到 head
字段。
在 Learning Rust With Entirely Too Many Linked Lists 中,它们表明 pub enum
不能容纳私有 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
是私有的,这段代码也不会导致错误:
pub struct List {
head: Link,
}
enum Link {
Empty,
More(Box<Node>),
}
struct Node {
elem: i32,
next: Link,
}
造成这种差异的原因是什么?为什么私有枚举不会导致错误而私有结构会导致错误?
在第一个例子中,枚举 List
是 public。这意味着枚举变体 More
也是 public。但是,More
不能被外部代码使用,因为 Node
不是 public。因此,你有一个外部可见的东西,但实际上不能使用,这可能不是你想要的。
在第二个例子中,结构List
是public。但是,head
字段是 而不是 public。因此,Link
是否为 public 并不重要,因为外部代码首先看不到 head
字段。