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

标签 generics rust traits

我有这个代码(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       
    }
} 

我想做的是保留give的签名性状的功能 Trait同时实现特征 Trait对于通用结构 Struct .

但是我得到了这个错误

<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       
                 ^~~~~~

我想使用我在这个 question 中看到的东西它将关联参数与通用参数相匹配,所以我更改了:

    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以适用于调用者希望的任何类型的方式。另一方面,您对 give 的实现对于 Struct<T>仅适用于特定 类型,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特质。

关于generics - 将泛型参数与 impl 的另一个泛型参数匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32407882/

相关文章:

generics - Kotlin中的简单泛型函数失败

c# - 我使用通用限制阻止特定类型

c# - 如果缺少元素,如何处理失败的 LINQ 表达式

java - 使用收集器将列表转换为对象映射 - Java

rust - 有没有更简单的方法在我的构建脚本上运行 clippy?

iterator - 将装箱值映射到 Rust 中的可变取消引用值

generics - 如何避免将具体结构更改为通用结构所产生的链式 react ?

rust - Rust提示通用参数不满足特征界限,即使它不是必需的

rust - 为什么不能将盒装结构作为特征借用?

types - 我得到了一个预期的类型参数,尽管我认为我已经返回了正确的类型数据