如何在 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 没有 "templates specialization"。那么,有什么方法可以在 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
}
我需要测试 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 没有 "templates specialization"。那么,有什么方法可以在 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
}