In general case, it is not possible to implement in crate C1 a trait defined in C2 for a Type defined in crate C3, being assumed that C1, C2, C3 are different

But is there a trick to designing a trait on purpose, so that such implementations are allowed?

推荐答案

No. There is no such thing, as it is fundamentally flawed because it allows collisions between impls.

For example, you can upgrade a minor version of a dependency, then your code won't compile because in the minor version they added a dependency of their on some crate that had some impl for trait, and you already have a dependency that has a colliding impl.

There are some ways to relax coherence, but all are unstable and none are the same as what you want:

  • Negative impls allow you to promise some trait will never be implemented for some type, allowing othwerise potentially overlapping impls - but does not affect the orphan checks at all;
  • Fundamental types allow you to promise a type will not add a blanket impl, allowing you to impl foreign traits for type wrapped in them (this is the reason you can, for example, impl a foreign trait on Box<LocalType>) - but does not allow to implement foreign traits on any type;
  • Fundamental traits are traits that adding a blanket implementation for them is a breaking change (although the teams want to get rid of them). This is more general than negative impls (too general even, which is why they want to get rid of it), but still as far as I can tell only affects overlap check.

Rust相关问答推荐

重新导出proc宏导致未解决的extern crate错误""

在HashMap中插入Vacant条目的可变借位问题

访问Rust中的隐藏变量

创建Rust中元对象协议的动态对象 Select /重新分配机制

如何在函数中返回自定义字符串引用?

循环访问枚举中的不同集合

在Rust中克隆源自INTO_ITER()的迭代器的成本?

考虑到Rust不允许多个可变引用,类似PyTorch的自动区分如何在Rust中工作?

从管道读取后重置标准输入

如何将一个矩阵的列分配给另一个矩阵,纳尔代数?

如何正确使用git2::Remote::push?

Rust中的标记特征是什么?

如何在 Rust 的 Hyper 异步闭包中从外部范围正确读取字符串值

无法理解 Rust 对临时值的不可变和可变引用是如何被删除的

使用部分键从 Hashmap 中检索值

如何在 Rust 中创建最后一个元素是可变长度数组的 struct ?

TinyVec 如何与 Vec 大小相同?

为什么-x试图解析为文字并在声明性宏中失败?

Rust 生命周期:不能在方法内重新borrow 可变字段

将 reqwest bytes_stream 复制到 tokio 文件中