如何检查Box是否为空指针?
我想使用指针或其他东西来实现堆栈。如何检查 aBox是否为空指针?我看过一些代码Option<Box<T>>和Box<Option<T>>,但我不明白这一点。就我而言,这是:
struct Node {
value: i32,
next: Box<Node>,
}
struct Stack {
top: Box<Node>,
}
回答
Box<T> 永远不能为 NULL,因此无需检查。
Box<T>值将始终完全对齐,非空指针—
std::box
您最有可能希望使用Option来表示值的缺失/存在:
struct Node {
value: i32,
next: Option<Box<Node>>,
}
struct Stack {
top: Option<Box<Node>>,
}
struct Node {
value: i32,
next: Option<Box<Node>>,
}
struct Stack {
top: Option<Box<Node>>,
}
也可以看看:
- 我们应该使用 Option 还是 ptr::null 来表示 Rust 中的空指针?
- 如何在具有空值的结构中设置字段?
- Rust 中的空指针优化是什么?
回答
你不想null。null即使在您必须使用它的语言中,它也是一种不安全的反模式,幸运的是 Rust 使我们摆脱了这种暴行。Box<T> 总是包含一个T,从不 null。Rust 没有null.
正如您正确指出的那样,如果您希望某个值是可选的,请使用Option<T>. 无论你做Box<Option<T>>还是Option<Box<T>>真的都没有那么重要,对事物的低级方面了解得更多的人可以插话说哪个更有效。
该Option说,“这可能会或可能不存在”,并且Box说“这个值是在堆上。现在,有关的好处Option,使得它无限美好的比null的是,你必须检查它。你不能忘记或编译器会抱怨。这样做的典型方法是match
match my_stack.top {
None => {
// Top of stack is not present
}
Some(x) => {
// Top of stack exists, and its value is x of type Box<T>
}
}
有吨的辅助方法的Option类型本身应对常见的模式。以下只是我使用的一些最常见的。请注意,所有这些都可以根据match便利功能来实现。
等效于以下 Java 代码
if (value == null) {
result = null;
} else {
result = ...;
}
是
let result = value.map(|v| ...)
或者,如果内部计算也可以可行地产生None,
let result = value.and_then(|v| ...)
如果要提供默认值,请说零,例如
if (value == null) {
result = 0;
} else {
result = value;
}
那你要
result = value.unwrap_or(0)
最好停止思考如何处理null并Option<T>从头开始学习。一旦你掌握了它,你就会觉得它比null支票更安全、更符合人体工程学。
- Re ordering, prefer `Option<Box<T>>`. Done the other way you're dynamically allocating just so you can say you have nothing. Since Box is never null, `Option<Box<T>>` will use the null pointer bit pattern to store `None` for the option, for free.
- In all honesty, and I mean this sincerely, based on this question and the one Shepmaster linked, my best advice to you is to slow down and read a good Rust tutorial. It seems like you're expecting Rust to be "C++ with funny syntax", but it's really not. It's an entirely different abstraction scheme, and the borrow checker has no real equivalent in any other mainstream language. Approach it like an entirely new paradigm. It'll do wonders.