rust - 通用特征实现错误
问题描述
这个特征声明和定义可以正常工作,没有任何问题:
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 认为您正在使用与类型 bounds 相关的不稳定特性,这导致了令人困惑的错误消息。
还有一些其他问题,我设法解决了(游乐场):
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)
}
推荐阅读
- python - 分享:我在 python 3 中做了一些计时器!这里是:
- javascript - 如何让 javascript 和 python 在电话应用程序中一起通信?
- python - Python pandas 将 mongodb 集合乱序导出到 CSV 列
- visual-studio-code - 是否可以使用特定文件在启动时更改 vscode 状态栏颜色?
- json - 如何在不调用 api 的情况下检索记录列表
- react-native - 未设置导航标题
- sql - 用于验证日期范围的 SQL 索引
- c# - 如何更新只有外键的表
- logging - Kubernetes:如何使用 sidecar 容器收集 stdout/stderr 日志
- javascript - Laravel Livewire and Cashier double form submit issue