假设我的工作区中有 2 个库 crate:A 和 B。在 crate A 中,我创建了一个公共结构
StructA
。箱子 B 依赖于箱子 A,并且在 src/lib.rs
中有以下代码:
use A::StructA;
struct StructB;
impl<T: Into<StructA>, E> From<Result<T, E>> for StructB {
fn from(value: Result<T, E>) -> Self {
Self
}
}
impl<T: Into<StructA>> From<T> for StructB {
fn from(value: T) -> Self {
println!("Into StructB!"); // included so the implementations are different
Self
}
}
上面的代码将无法编译并给出警告:
note: upstream crates may add a new impl of trait `std::convert::From<std::result::Result<_, _>>` for type `A::StructA` in future versions
我面临的问题与另一个问题中提出的问题类似。与提出这个问题的人不同,我实际上可以控制上游板条箱是否为
From<Result<_, _>>
实现 StructA
。有没有办法让板条箱 A 的依赖者清楚地知道它永远不会在以后的版本中添加特定的 impl?
其实还有这样的方法!
但它不会让你满意,因为它是夜间专用的,并且是标准的内部功能。不过,lang 团队可能会决定在未来公开它。
这是通过负面暗示完成的。
在板条箱中
A
:
#![feature(negative_impls)]
impl<T: Into<StructA>, E> !Into<StructA> for Result<T, E> {}
在板条箱中
B
:
#![feature(with_negative_coherence)]
use A::StructA;
struct StructB;
impl<T: Into<StructA>, E> From<Result<T, E>> for StructB {
fn from(value: Result<T, E>) -> Self {
Self
}
}
impl<T: Into<StructA>> From<T> for StructB {
fn from(value: T) -> Self {
println!("Into StructB!"); // included so the implementations are different
Self
}
}