Is it possible to match against a NULL pointer in Rust?

为君一笑 提交于 2021-01-27 06:08:47

问题


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))
    }
}

回答1:


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:

Your code would look something like

fn do_stuff(ptr: *const i32) -> Option<i32> {
    let ptr = unsafe { ptr.as_ref() };
    ptr.map(|x| do_transform(x, 42))
}


来源:https://stackoverflow.com/questions/37466676/is-it-possible-to-match-against-a-null-pointer-in-rust

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