是否可以在特征上具有通用功能? [英] Is it possible to have a generic function on a trait?
问题描述
我有:
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
做任何事情,但是取决于Grumbo
和T
,如果对特定的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 arbitraryT
without specializing myPlumbus
for a particularT
?
推荐答案
是否可以在特征上具有通用功能?
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屋!