Luk*_*odt 7 language-lawyer rust
尝试将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
}
}
Run Code Online (Sandbox Code Playgroud)
很简单。这样,将编译以下代码:
let a = String::from("a");
let b = String::from("b");
MyAdd::add(a, &b);
Run Code Online (Sandbox Code Playgroud)
请注意,在这种情况下,第二个参数表达式(&b)具有类型&String。然后将其反强制执行&str,然后函数调用起作用。
但是,让我们尝试添加以下内容:
impl MyAdd<char> for String {
fn add(mut self, rhs: char) -> Self {
self.push(rhs);
self
}
}
Run Code Online (Sandbox Code Playgroud)
(操场上的一切)
现在,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>>
Run Code Online (Sandbox Code Playgroud)
这是为什么?对我来说,似乎只有在只有一个候选函数时才执行反强制。但这对我来说似乎是错误的。为什么规则会这样?我尝试浏览该规范,但在参数deref强制上未找到任何内容。
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |