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

Matching a generic parameter to another generic parameter of an impl

我有这个代码 (in playground):

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 函数的签名,同时为通用结构 Trait 实现特征 Trait =17=].

但是我收到这个错误

<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.

如何使特征本身成为通用的,而不是方法?

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 特征。