【问题标题】:Function pointers in Rust using constrained genericsRust 中使用约束泛型的函数指针
【发布时间】:2017-11-18 08:27:43
【问题描述】:

我正在尝试创建一个如下所示的结构:

struct MediaLibrary<B>
where
    B: Ord,
{
    root_dir: PathBuf,
    item_meta_fn: String,
    self_meta_fn: String,
    media_item_filter: fn(&Path) -> bool,
    media_item_sort_key: fn(&Path) -> B,
}

最后两个字段分别用作测试给定路径是否为有效媒体文件的谓词,并对路径向量进行排序(使用sort_by_key)。

但是,就像现在一样,设计不灵活:两个函数都固定为只接受Path。我希望能够使用 P: AsRef&lt;Path&gt; 作为 stdlib 用于其许多文件和路径方法的方法,但我不知道如何添加它。

implMediaLibrary 使用的许多方法已经在使用P: AsRef&lt;Path&gt; 作为它们的论点,所以我的直觉告诉我会有冲突。

【问题讨论】:

  • 为什么它们必须是函数指针而不是闭包?
  • 嗨,Shep,他们没有理由这样做!我不熟悉闭包的类型定义,那些是Fn/FnMut/FnOnce trait?
  • 没错,函数指针本身就实现了这些特征,因此它们可以在同一个地方使用。但是,我不确定是否真的能解决您的问题。
  • 我错过了什么棘手的问题吗?似乎我需要在where 中使用where,例如:media_item_filter: F where F: Fn(P) -&gt; bool; where P: AsRef&lt;Path&gt;

标签: generics rust


【解决方案1】:

据我所知,你不能拥有一个泛型类型的函数指针,我什至认为 Rust 解析器不接受这样的构造。

此外,您不能简单地切换到结构上的额外类型参数,因为它们将不会被结构本身使用:

struct MediaLibrary<F, P1, K, P2, B>
where
    F: Fn(P1) -> bool,
    P1: AsRef<Path>,
    K: Fn(P2) -> B,
    P2: AsRef<Path>,
    B: Ord,
{
    root_dir: PathBuf,
    item_meta_fn: String,
    self_meta_fn: String,
    media_item_filter: F,
    media_item_sort_key: K,
}
error[E0392]: parameter `P1` is never used
 --> src/main.rs:3:24
  |
3 | struct MediaLibrary<F, P1, K, P2, B>
  |                        ^^ unused type parameter
  |
  = help: consider removing `P1` or using a marker such as `std::marker::PhantomData`

相反,您可以选择仅将约束应用于使用它们的函数:

struct MediaLibrary<F> {
    media_item_filter: F,
}

impl<F> MediaLibrary<F> {
    fn do_filter<P>(&self)
    where
        F: Fn(P) -> bool,
        P: AsRef<Path>,
    {}
}

如消息所述,您也可以使用PhantomData

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多