在特征对象中使用泛型类型参数会引起什么问题? [英] What is the cited problem with using generic type parameters in trait objects?

查看:125
本文介绍了在特征对象中使用泛型类型参数会引起什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读

I am reading Object Safety Is Required for Trait Objects and I don't understand the problem with generic type parameters.

使用特征时,用具体类型参数填充的泛型类型参数也是如此:具体类型成为实现特征的类型的一部分.如果通过使用trait对象而忘记了类型,则无法知道用什么类型来填充通用类型参数.

The same is true of generic type parameters that are filled in with concrete type parameters when the trait is used: the concrete types become part of the type that implements the trait. When the type is forgotten through the use of a trait object, there is no way to know what types to fill in the generic type parameters with.

我正在尝试编写示例,但我无法理解. 什么的通用类型参数?

I am trying to code an example but I can't make sense of it. Generic type parameters for what?

我试图用参数化的特征制作一个特征对象,但是一旦给了该参数一个具体的值,它就可以正常工作:

I tried to make a trait object out of a parameterized trait, but once the parameter is given a concrete value it works just fine:

trait Creator<T> {
    fn create(&self) -> T;
}

struct CreationHouse {
    creators: Vec<Box<dyn Creator<u32>>>
}

struct NumCreator { seed: u32 }

impl Creator<u32> for NumCreator {
    fn create(&self) -> u32 {
        return self.seed;
    }
}

fn main() {
    let ch = CreationHouse{
        creators: vec![Box::new(NumCreator{seed: 3})]
    };
}

(编译良好,除了未使用"警告外)

(Compiles well, except "unused" warnings)

我不明白的是,使用特征时使用具体类型参数填充的泛型参数"是什么,以及泛型类型如何丢失(因为特征本身携带携带"它们) ).如果您能写出段落中描述的案例的例子,我将不胜感激.

What I don't get is what does it mean "generic type parameters that are filled in with concrete type parameters when the trait is used" and how could the generic types be lost (as the trait "carries" them with itself). If you could write an example of the case described in the paragraph I'd be grateful.

推荐答案

使用特征时使用具体类型参数填充的泛型类型参数"是什么意思

what does it mean "generic type parameters that are filled in with concrete type parameters when the trait is used"

当type参数是方法的一部分时,一个不起作用的示例:

An example that won't work is when the type parameter is part of a method:

trait Foo {
    fn foo<T>(t: T) {}
}

当一个函数具有类型参数时,Rust会针对实际使用的每种类型对函数进行单态化(创建新副本).这与特征对象不兼容,因为Rust在运行时才知道该方法属于哪个隐含对象.

When a function has a type parameter, Rust will monomorphize the function (make a new copy) for each type that it is actually called with. This isn't compatible with trait objects because Rust doesn't know which impl the method belongs to until runtime.

这篇关于在特征对象中使用泛型类型参数会引起什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆