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

試著忘記壹切 提交于 2019-12-02 09:58:31

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.

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

struct Plumbus<'a, T: Gumbo> { 
    grumbo: &'a 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.

See also:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!