gpt4 book ai didi

rust - 派生特征会导致意外的编译器错误,但手动实现有效

转载 作者:行者123 更新时间:2023-12-03 11:31:14 25 4
gpt4 key购买 nike

此代码(playground):

#[derive(Clone)]
struct Foo<'a, T: 'a> {
t: &'a T,
}

fn bar<'a, T>(foo: Foo<'a, T>) {
foo.clone();
}
...不编译:
error[E0599]: no method named `clone` found for struct `Foo<'a, T>` in the current scope
--> src/main.rs:16:9
|
3 | struct Foo<'a, T: 'a> {
| ---------------------
| |
| method `clone` not found for this
| doesn't satisfy `Foo<'_, T>: std::clone::Clone`
...
16 | foo.clone();
| ^^^^^ method not found in `Foo<'a, T>`
|
= note: the method `clone` exists but the following trait bounds were not satisfied:
`T: std::clone::Clone`
which is required by `Foo<'_, T>: std::clone::Clone`
help: consider restricting the type parameter to satisfy the trait bound
|
3 | struct Foo<'a, T: 'a> where T: 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 和手动的?
  • 这是编译器错误吗?
  • 还有什么我没想到的?
  • 最佳答案

    答案隐藏在错误消息中:

        = note: the method `clone` exists but the following trait bounds were not satisfied:
    `T: std::clone::Clone`
    which is required by `Foo<'_, T>: std::clone::Clone`

    当你推导出 Clone (以及许多其他自动派生的类型),它添加了 Clone绑定(bind) 全部 泛型类型。使用 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)),},
    }
    }
    }
    在这种情况下,不需要绑定(bind),因为泛型类型位于引用后面。
    现在,您需要实现 Clone你自己。 There's a Rust issue for this ,但这是一个相对罕见的解决方法。

    关于rust - 派生特征会导致意外的编译器错误,但手动实现有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65683427/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com