是否可以匹配 Rust 中的 NULL 指针? [英] Is it possible to match against a NULL pointer in Rust?
本文介绍了是否可以匹配 Rust 中的 NULL 指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
调用 is_null()
感觉有点奇怪:
Calling is_null()
feels a bit odd:
fn do_stuff(ptr: *const i32) -> Option<i32> {
if ptr.is_null() {
None
} else {
Some(do_transform(*ptr, 42))
}
}
推荐答案
从 Rust 1.9 开始,有一个 函数 as_ref
将原始指针转换为 Option<&T>
和可变变体 as_mut
:
As of Rust 1.9, there's a function as_ref
that converts a raw pointer to an Option<&T>
, and a mutable variant as_mut
:
你的代码看起来像
fn do_stuff(ptr: *const i32) -> Option<i32> {
let ptr = unsafe { ptr.as_ref() };
ptr.map(|x| do_transform(x, 42))
}
这篇关于是否可以匹配 Rust 中的 NULL 指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文