此代碼(操場):#[derive(Clone)]struct Foo<'a, T: 'a> { t: &'a T,}fn bar<'a, T>(foo: Foo<'a, T>) { foo.clone();}...無法編譯:error: no method named `clone` found for type `Foo<'a, T>` in the current scope --> <anon>:7:9 |>16 |> foo.clone(); |> ^^^^^note: the method `clone` exists but the following trait bounds were not satisfied: `T : std::clone::Clone`help: items from traits can only be used if the trait is implemented and in scope; the following trait defines an item `clone`, perhaps you need to implement it:help: candidate #1: `std::clone::Clone`添加use std::clone::Clone;并不會改變任何內容,因為它已經在序幕中了。當我刪除#[derive(Clone)]并手動實現Clone時Foo,它會按預期編譯!impl<'a, T> Clone for Foo<'a, T> { fn clone(&self) -> Self { Foo { t: self.t, } }}這里發生了什么?#[derive()]-impls和手動的之間有區別嗎?這是編譯器錯誤嗎?還有我沒想到的東西?
2 回答

天涯盡頭無女友
TA貢獻1831條經驗 獲得超9個贊
答案隱藏在錯誤消息中:
該方法clone存在,但不滿足以下特征范圍:T : std::clone::Clone
當您派生Clone(以及許多其他自動派生的類型)時,它會Clone在所有通用類型上添加一個界限。使用rustc -Z unstable-options --pretty=expanded,我們可以看到它變為:
impl <'a, T: ::std::clone::Clone + 'a> ::std::clone::Clone for Foo<'a, T> {
#[inline]
fn clone(&self) -> Foo<'a, T> {
match *self {
Foo { t: ref __self_0_0 } =>
Foo{t: ::std::clone::Clone::clone(&(*__self_0_0)),},
}
}
}
在這種情況下,不需要綁定,因為泛型類型在引用后面。
現在,您將需要實現Clone自己。有一個Rust問題,但這是一種相對罕見的解決方法。
- 2 回答
- 0 關注
- 565 瀏覽
添加回答
舉報
0/150
提交
取消