2

如何在编译期确定某个类型是不是 Option

 2 years ago
source link: https://privaterookie.github.io/notes/rust/2022-02-17-%E7%BC%96%E8%AF%91%E6%9C%9F%E7%A1%AE%E5%AE%9A%E6%9F%90%E4%B8%AA%E7%B1%BB%E5%9E%8B%E6%98%AF%E4%B8%8D%E6%98%AFOption.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

如何在编译期确定某个类型是不是 Option

要求不管是 Option<T> 还是 std::option::Option<T>, 抑或是 type A = Option<usize> 都能检测.

有个使用过程宏检测的简单办法, 原理是利用类型为 Option<T> 的变量一定可以被赋值为 None, 否则编译器会报错.

过程宏实现


#[proc_macro]
pub fn assert_option(item: TokenStream) -> TokenStream {
    let ty = parse_macro_input!(item as TypePath);
    let expand = quote! {
        {
            let _: #ty = ::std::option::Option::None;
        }
    };
    TokenStream::from(expanded)
}

type M = Option<u8>;
// 编译成功
assert_option!(M);
// 编译失败
assert_option!(u8);

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK