是否可以在特征上具有通用功能? [英] Is it possible to have a generic function on a trait?

查看:96
本文介绍了是否可以在特征上具有通用功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

struct Plumbus<'a> {
    grumbo: &'a Grumbo,
}

trait Grumbo {
    fn dinglebop<T>(&self, x: &mut T) -> bool { false }
}

但是我得到了

error[E0038]: the trait `Grumbo` cannot be made into an object
 --> plumbus.rs:4:5
  |
4 |     grumbo: &'a Grumbo,
  |     ^^^^^^^^^^^^^^^^^^ the trait `Grumbo` cannot be made into an object
  |
  = note: method `dinglebop` has generic type parameters

我希望默认情况下不让dinglebop做任何事情,但是取决于GrumboT,如果对特定的Grumbo实现有意义的话,可能用T填充x.

I want to have dinglebop do nothing by default, but depending on the Grumbo and the T, possibly fill x with a T if it makes sense for that particular Grumbo implementation.

在C ++中,这可以通过部分专业化来实现.我不确定Rust的目标是什么.

In C++ this could probably be accomplished with partial specialization. I am not sure what to aim for with Rust.

  • 是否可以在特征上具有这样的通用功能?
  • 我如何实现对任意T使用dinglebop()而不将我的Plumbus专用于特定 T的目标?
  • Is it possible to have generic functions like this on a trait?
  • How do I accomplish my goal of having a dinglebop() for arbitrary T without specializing my Plumbus for a particular T?

推荐答案

是否可以在特征上具有通用功能?

Is it possible to have a generic function on a trait?

是的.但是您随后尝试将特征用作对象.如果特征具有泛型方法,则不能将其用作对象,但仍可以将其用作类型参数的绑定.

Yes. But you are then trying to use the trait as an object. If a trait has a generic method then you can't use it as an object, but you can still use it as a bound for a type parameter.

也就是说,不要使用&'a Gumbo,而是使用T: Gumbo:

That is, instead of using &'a Gumbo, use a T: Gumbo:

struct Plumbus<'a, T: Gumbo> { 
    grumbo: &'a T,
}

使用trait对象,仅在运行时知道实现.而且它的通用参数是实现类型的一部分,因此编译器不知道如何调用它.使用T: Gumbo可以限制T的范围,但是T在使用时将始终被编译器知道,其中包括其自己的任何参数.

With the trait object, the implementation is only known at runtime. And its generic parameter is part of the implementation type, so the compiler couldn't know how to call it. With T: Gumbo you are putting a constraint on what T can be, but T will always be known by the compiler at the point of use, which includes any parameters of its own.

另请参阅:

  • Understanding Traits and Object Safety
  • What makes something a "trait object"?

这篇关于是否可以在特征上具有通用功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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