【发布时间】:2020-06-20 12:45:56
【问题描述】:
我不知道如何将sort 方法提供给Vec 实现中的https://doc.rust-lang.org/std/vec/struct.Vec.html#method.sort 作为参数。
我的代码受此问题Is it possible to pass an object method as argument to a function and bind it to the object? 中的代码启发,但不会编译。
这是我想做的一些示例代码,
fn pass_sort<F>(list: &mut Vec<i32>, sort_func: F)
where F: Fn(&mut Vec<i32>)
{
sort_func(list);
}
fn main() {
let mut list: Vec<i32> = vec![3, 2, 1];
pass_sort(&mut list, Vec::sort);
}
这是错误
error[E0599]: no function or associated item named `sort` found for struct `std::vec::Vec<_>` in the current scope
--> stak_test.rs:9:31
|
9 | pass_sort(&mut list, Vec::sort);
| ^^^^ function or associated item not found in `std::vec::Vec<_>`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0599`.
我猜这是因为sort 不是Vec 的方法,而是文档中解释的Deref<Target=[T]> 实现的方法,但我不知道如何从这个范围访问该方法:/。
【问题讨论】:
-
除了答案中的内容之外,另一种选择是使用闭包:
pass_sort(&mut list, |v| v.sort())。由于 Rust 的闭包是零成本(尽可能内联),我希望它会生成完全相同的代码。
标签: rust