gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:26:44 25 4
gpt4 key购买 nike

我想获取给定类型 T 的一些 TypeId 实例,它实现了 Sized + 'static

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 unstable 特性来实现。

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>());
}

关于types - 我如何在 Rust 中获得 `std::any::TypeId::of` 超过 `T` 、 `&T` 和 `&mut` T 的相同结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66524465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com