如果对通用结构使用通用实现,则会出错。我应该如何向编译器解释last
函数返回可以在减法运算中使用的数据?
use std::ops::Sub;
struct Container<A, B>(A, B);
trait Contains {
type A;
type B;
fn contains(&self, &Self::A, &Self::B) -> bool;
fn first(&self) -> Self::A;
fn last(&self) -> Self::B;
}
impl<C: PartialEq, D: PartialEq + Sub> Contains for Container<C, D> {
type A = C;
type B = D;
fn contains(&self, number_1: &Self::A, number_2: &Self::B) -> bool {
(&self.0 == number_1) && (&self.1 == number_2)
}
fn first(&self) -> Self::A {
self.0
}
fn last(&self) -> Self::B {
self.1
}
}
fn difference<C: Contains>(container: &C) -> i32 {
container.last() - container.first()
}
fn main() {
let number_1 = 3;
let number_2 = 10;
let container = Container(number_1, number_2);
println!("Does container contain {} and {}: {}",
&number_1,
&number_2,
container.contains(&number_1, &number_2));
println!("First number: {}", container.first());
println!("Last number: {}", container.last());
println!("The difference is: {}", difference(&container));
}
我收到错误:
error[E0369]: binary operation `-` cannot be applied to type `<C as Contains>::B`
--> src/main.rs:30:5
|
30 | container.last() - container.first()
| ^^^^^^^^^^^^^^^^
|
= note: an implementation of `std::ops::Sub` might be missing for `<C as Contains>::B`
答案 0 :(得分:2)
这是一个有趣的类型俄罗斯方块来弄清楚:)
其他人可能能够更好地实施您尝试执行的操作,但我至少可以解释为什么您的代码无法编译。
有四个问题:
difference
的实施对Contains
的所有实施都是通用的,因此仅对Container
&#39; s进行限制是不够的类型 - 你也需要把它们放在特质上。
因为您试图从Self::A
类型的对象中减去Self::B
类型的对象,所以您需要在约束中指定它 - 它默认为{{ 1}}。
Rust不会将Sub<Self>
的结果隐式转换为difference
- 您需要对i32
的返回值进行泛型处理,或者添加显式转换(将涉及添加更多类型约束)。我做了前者,因为它似乎更符合你想要实现的目标。
difference
和first
尝试将last
和self.0
的所有权移出结构 - 您需要让它们返回借用(这将涉及终身恶作剧,或限制self.1
仅允许Contains
类型。
进行这些更改后,您的代码将如下所示:
Copy
编译并运行良好:
use std::ops::Sub;
struct Container<A, B>(A, B);
trait Contains {
type A: Copy + PartialEq;
type B: Copy + PartialEq + Sub<Self::A>;
fn contains(&self, &Self::A, &Self::B) -> bool;
fn first(&self) -> Self::A;
fn last(&self) -> Self::B;
}
impl<C, D> Contains for Container<C, D>
where
C: Copy + PartialEq,
D: Copy + PartialEq + Sub<C>,
{
type A = C;
type B = D;
fn contains(&self, number_1: &Self::A, number_2: &Self::B) -> bool {
(&self.0 == number_1) && (&self.1 == number_2)
}
fn first(&self) -> Self::A {
self.0
}
fn last(&self) -> Self::B {
self.1
}
}
fn difference<C: Contains>(
container: &C,
) -> <<C as Contains>::B as std::ops::Sub<<C as Contains>::A>>::Output {
container.last() - container.first()
}
fn main() {
let number_1 = 3;
let number_2 = 10;
let container = Container(number_1, number_2);
println!(
"Does container contain {} and {}: {}",
&number_1,
&number_2,
container.contains(&number_1, &number_2)
);
println!("First number: {}", container.first());
println!("Last number: {}", container.last());
println!("The difference is: {}", difference(&container));
}
我注意到如果Does container contain 3 and 10: true
First number: 3
Last number: 10
The difference is: 7
总是只包含数字类型,那么您可能能够使用{{3}更轻松地实现这一点},如num
crate。