A
当和的某种组合B
未实现时,您不能强制编译器发出错误save
。但是您可以拥有一个通用功能,该功能需要特定的组合A
和B
它接收的实现save
。
为此,我们需要包装save
一个 trait 并在包含A
and的某种类型上实现它B
;最简单的选择是元组。(但是,如果 trait 和类型不在同一个 crate 中,则连贯性可能会妨碍。)
trait Save {
fn save(self);
}
struct Foo; // sample save source
struct Bar; // sample save destination
// save is defined for the combination of `Foo` and `Bar`
impl Save for (Foo, Bar) {
fn save(self) {
unimplemented!()
}
}
// in order to call this, the type `(A, B)` must implement `Save`
fn call_save<A, B>(a: A, b: B)
where
(A, B): Save
{
(a, b).save();
}
fn main() {
// this call compiles because `impl Save for (Foo, Bar)` is present
call_save(Foo, Bar);
}
您也可以这样做以供参考:
trait Save {
fn save(self);
}
struct Foo;
struct Bar;
impl<'a, 'b> Save for (&'a Foo, &'b Bar) {
fn save(self) {
unimplemented!()
}
}
fn call_save<'a, 'b, A, B>(a: &'a A, b: &'b B)
where
(&'a A, &'b B): Save
{
(a, b).save();
}
fn main() {
call_save(&Foo, &Bar);
}