【发布时间】:2015-09-04 23:23:46
【问题描述】:
我有这个代码 (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
}
}
我想要做的是保留特征Trait 的give 函数的签名,同时为通用结构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
^~~~~~
我想使用我在这个question 中看到的,它将关联参数与通用参数匹配,所以我更改了:
fn give<S>(&self, x: S) -> S
where S: Limit
到:
fn give<S = T>(&self, x: S) -> S
where S: Limit
我没有收到有关此语法的错误,但这不是上述错误的解决方案。
有什么方法可以实现我想做的吗?
还有一个附带问题,<S = T> 在这种情况下实际上做了什么?
【问题讨论】: