繁体   English   中英

如何在 Rust 中通过 `T`、`&T` 和 `&mut` T 获得相同的 `std::any::TypeId::of` 结果?

[英]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不稳定特性来实现。

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=4c5f206ef3a7843ed57c256ee73ac58c

#![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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM