Rust enforces coherence to avoid trait resolution ambiguities. For example:
- Trait
Noise
with implementation forCat
causing a conflict. - Sometimes an API wants to violate coherence, like implementing a trait for functions with different numbers of parameters. But a straightforward trait definition leads to a compiler error.
To work around this, introduce a trait parameter M
to prevent conflicts. For example:
trait Noise<M> { fn make_noise(&self); }
with implementations forCat
and differentM
values.- To call
make_noise
, a fully-qualified path may be needed like<Cat as Noise<Quiet>>::make_noise(&Cat)
.
To disambiguate tacit parameters:
- Implement
Noise
for functions with the tacit trait parameter as a tuple of function parameters. - This allows calling
make_noise
without errors, like for a functiondog
.
Alternative applications:
- Haven't seen other uses yet. It's a feature to use carefully.
- In some cases with a fluent API and context to disambiguate tacit trait parameters. For example, in
PetList
withLoud
orQuiet
pets.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。