[英]How can I get same result of `std::any::TypeId::of` over `T`, `&T` and `&mut` T in Rust?
我想为实现Sized + 'static
的给定类型T
获取一些TypeId
实例。
use std::any::TypeId;
trait Comp: Sized + 'static { }
impl<T: 'static> Comp for T { }
struct Foo;
fn main() {
println!("{}", TypeId::of::<Foo>());
println!("{}", TypeId::of::<&Foo>());
println!("{}", TypeId::of::<&mut Foo>());
}
但结果不同。 是的,我知道这是完全正常的行为。 为了处理这个问题,我修改了这段代码,如下所示。
use std::ops::Deref;
// Same codes are omitted...
fn main() {
println!("{}", TypeId::of::<Foo>());
println!("{}", TypeId::of::<<&Foo as Deref>::Target>());
println!("{}", TypeId::of::<<&mut Foo as Deref>::Target>());
}
现在它打印相同的值。 为了对所有Comp
实现这种行为,我在下面写道。
use std::any::TypeId;
use std::ops::Deref;
trait Comp: Sized + 'static {
type Pure: Comp;
}
impl<T: 'static> Comp for T {
type Pure = T;
}
impl<T: Deref + 'static> Comp for T {
type Pure = <T as Deref>::Target;
}
struct Foo;
fn main() {
println!("{}", TypeId::of::<<Foo as Comp>::Pure>());
println!("{}", TypeId::of::<<&Foo as Comp>::Pure>());
println!("{}", TypeId::of::<<&mut Foo as Comp>::Pure>());
}
它不会编译,因为我提供了冲突的实现。 我怎么解决这个问题?
终于在Rust的官方社区找到了解决办法。 它可以通过specialization
不稳定特性来实现。
#![feature(specialization)]
use std::any::TypeId;
use std::ops::Deref;
trait Comp: Sized {
type Pure: Comp;
}
impl<T> Comp for T {
default type Pure = T;
}
impl<T: Deref> Comp for T where <T as Deref>::Target: Comp {
type Pure = <T as Deref>::Target;
}
struct Foo;
fn main() {
println!("{:?}", TypeId::of::<<Foo as Comp>::Pure>());
println!("{:?}", TypeId::of::<<&Foo as Comp>::Pure>());
println!("{:?}", TypeId::of::<<&mut Foo as Comp>::Pure>());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.