【问题标题】:Giving a method as a parameter in Rust (Vec sort() method)在 Rust 中将方法作为参数提供(Vec sort() 方法)
【发布时间】: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&lt;Target=[T]&gt; 实现的方法,但我不知道如何从这个范围访问该方法:/。

【问题讨论】:

  • 除了答案中的内容之外,另一种选择是使用闭包:pass_sort(&amp;mut list, |v| v.sort())。由于 Rust 的闭包是零成本(尽可能内联),我希望它会生成完全相同的代码。

标签: rust


【解决方案1】:

我猜这是因为 sort 不是 Vec 的方法,而是 Deref 的方法

没错,方法来自slice::sort,所以需要改用:

fn pass_sort<F>(list: &mut Vec<i32>, sort_func: F)
where
    F: Fn(&mut [i32]),
{
    sort_func(list);
}

fn main() {
    let mut list: Vec<i32> = vec![3, 2, 1];
    pass_sort(&mut list, <[i32]>::sort);
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多