如何在 Rust 中测试类型相等性?

炸鱼薯*_*德里克 5 metaprogramming rust

我需要测试两种类型在const fn. 比较TypeId不起作用:

#![feature(const_if_match)]
#![feature(const_fn)]
#![feature(const_type_id)]

const fn t<T1: 'static, T2: 'static>() -> bool{
    std::any::TypeId::of::<T1>() == std::any::TypeId::of::<T2>()
}
Run Code Online (Sandbox Code Playgroud)

错误:

#![feature(const_if_match)]
#![feature(const_fn)]
#![feature(const_type_id)]

const fn t<T1: 'static, T2: 'static>() -> bool{
    std::any::TypeId::of::<T1>() == std::any::TypeId::of::<T2>()
}
Run Code Online (Sandbox Code Playgroud)

C++ 中的模板特化在 Rust 中不起作用,因为 Rust 没有“模板特化”。那么,有没有办法在 Rust 中测试类型相等性?

Frx*_*rem 7

如果你每晚都在使用 Rust(看起来你是这样),你可以使用不稳定的specialization特性和一些辅助特性来做到这一点:

#![feature(specialization)]

/// Are `T` and `U` are the same type?
pub const fn type_eq<T: ?Sized, U: ?Sized>() -> bool {
    // Helper trait. `VALUE` is false, except for the specialization of the
    // case where `T == U`.
    trait TypeEq<U: ?Sized> {
        const VALUE: bool;
    }

    // Default implementation.
    impl<T: ?Sized, U: ?Sized> TypeEq<U> for T {
        default const VALUE: bool = false;
    }

    // Specialization for `T == U`.
    impl<T: ?Sized> TypeEq<T> for T {
        const VALUE: bool = true;
    }

    <T as TypeEq<U>>::VALUE
}
Run Code Online (Sandbox Code Playgroud)

操场上的例子