我在尝试将 impl 添加Add<char> for String到标准库时遇到了这个问题。但我们可以轻松复制它,无需操作员的恶作剧。我们从这个开始:
trait MyAdd<Rhs> {
fn add(self, rhs: Rhs) -> Self;
}
impl MyAdd<&str> for String {
fn add(mut self, rhs: &str) -> Self {
self.push_str(rhs);
self
}
}
很简单。有了这个,下面的代码编译:
let a = String::from("a");
let b = String::from("b");
MyAdd::add(a, &b);
请注意,在这种情况下,第二个参数表达式 ( &b) 的类型为&String。然后它被强制解引用&str并且函数调用起作用。
但是,让我们尝试添加以下 impl:
impl MyAdd<char> for String {
fn add(mut self, rhs: char) -> Self {
self.push(rhs);
self
}
}
(操场上的一切)
现在MyAdd::add(a, &b)上面的表达式导致以下错误:
error[E0277]: the trait bound `std::string::String: MyAdd<&std::string::String>` is not satisfied
--> src/main.rs:24:5
|
2 | fn add(self, rhs: Rhs) -> Self;
| ------------------------------- required by `MyAdd::add`
...
24 | MyAdd::add(a, &b);
| ^^^^^^^^^^ the trait `MyAdd<&std::string::String>` is not implemented for `std::string::String`
|
= help: the following implementations were found:
<std::string::String as MyAdd<&str>>
<std::string::String as MyAdd<char>>
这是为什么?对我来说,似乎只有在只有一个候选函数时才会执行 deref-coercion。但这对我来说似乎是错误的。为什么会有这样的规则?我尝试查看规范,但我没有找到任何关于参数 deref coercion 的内容。