gpt4 book ai didi

rust - 通用特征实现错误

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

此特征声明和定义可以正常工作,没有任何问题:

trait FTrait<T>: Fn(T, T) -> T {}
impl<T, F> FTrait<T> for F where F: Fn(T, T) -> T, {}
...
fn hof(f: impl FTrait<u32>) -> impl FTrait<u32> { //fourth with a generic trait in use with concrete types
move |a, b| {
let r = f(a, b);
r
}
}

但是此特征声明给出了多个错误:
    trait FTraitBorrowed<'a, T>: Fn(&'a T, &'a T) -> &'a T {}
impl<'a, T, F> FTraitBorrowed<'a, T: 'a, F> for F where F: Fn(&'a T, &T) -> &'a T, {}

....
fn hof_borrowed(f: impl FTraitBorrowed<i32>) -> impl FTraitBorrowed<i32 > {
move |a, b| {
let r = f(a, b);
r
}

错误在这里列出:
Errors:
error: associated type bindings must be declared after generic parameters
--> src\main.rs:44:31
|
44 | impl<'a, T, F> FTraitBorrowed<'a, T: 'a, F> for F where F: Fn(&'a T, &T) -> &'a T, {}
| ^^^^-----^^^
| |
| this associated type binding should be moved after the generic parameters

error[E0658]: associated type bounds are unstable
--> src\main.rs:44:35
|
44 | impl<'a, T, F> FTraitBorrowed<'a, T: 'a, F> for F where F: Fn(&'a T, &T) -> &'a T, {}
| ^^^^^
|
= note: for more information, see https://github.com/rust-lang/rust/issues/52662

error[E0229]: associated type bindings are not allowed here
--> src\main.rs:44:35
|
44 | impl<'a, T, F> FTraitBorrowed<'a, T: 'a, F> for F where F: Fn(&'a T, &T) -> &'a T, {}
| ^^^^^ associated type not allowed here

error: aborting due to 3 previous errors

Some errors have detailed explanations: E0229, E0658.
For more information about an error, try `rustc --explain E0229`.

无法从提示中清楚地了解出了什么问题。

对于第一个错误,如果我在实现中像这样互换F和T的位置,则该错误消失了:
impl<'a, T, F> FTraitBorrowed<'a, F, T: 'a, > ...

有人可以帮忙吗?

谢谢。

最佳答案

导致错误的问题是那里不允许类型边界:

// correct
impl<'a, T: 'a, F> FTraitBorrowed<'a, T, F> ...

// wrong
impl<'a, T, F> FTraitBorrowed<'a, T: 'a, F> ...

因此,Rust认为您正在使用不稳定的功能 associated type bounds,该功能导致了令人困惑的错误消息。

还有其他一些问题,我设法解决了( playground):

trait FTraitBorrowed<'a, T: 'a>: Fn(&'a T, &'a T) -> &'a T {}

impl<'a, T: 'a, F> FTraitBorrowed<'a, T> for F where F: Fn(&'a T, &'a T) -> &'a T {}

fn hof_borrowed<'a, F>(f: impl FTraitBorrowed<'a, i32>) -> impl FTraitBorrowed<'a, i32> {
move |a, b| f(a, b)
}

关于rust - 通用特征实现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61221653/

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