繁体   English   中英

将泛型参数与 impl 的另一个泛型参数匹配

[英]Matching a generic parameter to another generic parameter of an impl

我有这个代码(在操场上):

trait Limit {}

pub trait Trait
{
    fn give<T>(&self, x: T) -> T
    where T: Limit;
}

struct Struct<T: Limit> {field: T}

impl<T> Trait for Struct<T>
    where T: Limit
{   
    fn give<S>(&self, x: S) -> S 
    where S: Limit
    {
       self.field
       //interacts with x parameter and gives an "S: Limit" result       
    }
} 

我想要做的是保留特征Traitgive函数的签名,同时为通用结构Struct实现特征Trait

但我收到这个错误

<anon>:17:8: 17:14 error: mismatched types:
 expected `S`,
    found `T`
(expected type parameter,
    found a different type parameter) [E0308]
<anon>:17        self.field       
                 ^~~~~~

我想使用我在这个问题中看到的将关联参数与泛型参数相匹配的内容,因此我进行了更改:

    fn give<S>(&self, x: S) -> S 
    where S: Limit

到:

    fn give<S = T>(&self, x: S) -> S 
    where S: Limit

我没有收到有关此语法的错误,但这不是上述错误的解决方案。

有什么办法可以实现我想做的事吗?

还有一个附带问题, <S = T>在这种情况下实际上做了什么?

当你写的,你的执行Trait必须实现give的方式,对任何类型的呼叫方希望工程。 另一方面,您对Struct<T>give实现仅适用于特定类型T

如何使 trait 本身而不是方法通用?

pub trait Trait<T> where T: Limit {
    fn give(&self, x: T) -> T;
}

impl<T> Trait<T> for Struct<T> where T: Limit {   
    fn give(&self, x: T) -> T 
    {
       self.field // does not compile, you can't give away one of your fields
                  // unless you mem::replace() it with another value
    }
} 

这样, Trait<T>的实现只适用于由实现者选择的特定T类型,而不是调用者。

另一种选择是使用关联类型:

pub trait Trait {
    type T: Limit;

    fn give(&self, x: Self::T) -> Self::T;
}

impl<T> Trait for Struct<T> where T: Limit {
    type T = T;

    fn give(&self, x: T) -> T 
    {
       self.field
    }
} 

在这里, Trait不再是通用的,但Struct仍然是通用的,并且每个Struct实例都实现了相同的Trait trait。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM