用隐式特征参数在 Rust 中击败一致性

Rust enforces coherence to avoid trait resolution ambiguities. For example:

  • Trait Noise with implementation for Cat 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 for Cat and different M 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 function dog.

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 with Loud or Quiet pets.
阅读 12
0 条评论