簡體   English   中英

如何測試 Rust 中的類型相等性?

[英]How to test for type equality in 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>()
}

錯誤:

error[E0015]: calls in constant functions are limited to constant functions, tuple structs and tuple variants
 --> src/lib.rs:5:8
  |
5 |     std::any::TypeId::of::<T1>()==std::any::TypeId::of::<T2>()
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

C++ 中的模板專業化在 Rust 中不起作用,因為 Rust 沒有“模板專業化”。 那么,有什么方法可以測試 Rust 中的類型相等性嗎?

如果你每晚都在使用 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
}

操場上的例子

OP的解決方案很接近:

// expects references
fn of_same_type<S: ?Sized + Any, T: ?Sized + Any>(_s: &S, _t: &T) -> bool {
    TypeId::of::<S>() == TypeId::of::<T>()
}

操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM