gpt4 book ai didi

rust - 如何将泛型函数转换为带有引用参数的函数指针?

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

pub fn remove_file<P: AsRef<Path>>(path: P) -> Result<()>;
我正在努力将 std::fs::remove_file 转换为函数指针:
Playground
use std::{io, fs, path::Path};

fn main() {
let _: fn(&Path) -> io::Result<()> = &fs::remove_file;

// let _: &dyn FnOnce(&Path) -> io::Result<()> = &fs::remove_file;
}
错误如下:
error[E0308]: mismatched types
--> src/main.rs:4:43
|
4 | let _: fn(&Path) -> io::Result<()> = &fs::remove_file;
| --------------------------- ^^^^^^^^^^^^^^^^ expected fn pointer, found reference
| |
| expected due to this
|
= note: expected fn pointer `for<'r> fn(&'r std::path::Path) -> std::result::Result<(), std::io::Error>`
found reference `&fn(_) -> std::result::Result<(), std::io::Error> {std::fs::remove_file::<_>}`
问题可能与 for<'r>高阶生存期要求有关,但我不知道如何解决。
如何使用特征对象?以下内容也不编译:
let _: &dyn FnOnce(&Path) -> io::Result<()> = &fs::remove_file;
我知道我可以围绕 fs::remove_file制作包装函数,但我想避免这种情况,并让 fs::remove_file成为函数指针或特征对象本身。
这不是此 Function pointers in Rust using constrained generics的副本,因为我想使用 std::fs::remove_file作为类型参数获取指向 &Path具体实例化的函数指针,但不具有泛型函数指针类型。
我尝试了以下操作,但也不起作用:
use std::{io, fs, path::Path};

fn main() {
let _: fn(&Path) -> io::Result<()> = &fs::remove_file::<&Path>;
}

最佳答案

I'd like to get a function pointer to the concrete instantiation of std::fs::remove_file with &Path as a type parameter, but not to have a generic function pointer type.


这是问题的核心。一个具体的实例将被编译。例如:
let _ : fn(&'static Path) -> io::Result<()> = fs::remove_file::<&'static Path>;
let _ : fn(&'r Path) -> io::Result<()> = fs::remove_file::<&'r Path>;
let _ : fn(&'long Path) -> io::Result<()> = fs::remove_file::<&'short Path>;
您尝试做的是从 fs::remove_file类型强制:
∀ P: AsRef<Path>, P → io::Result<()>
类型:
∀ 'r, &'r Path → io::Result<()>
在整个生命周期中,函数指针类型仍然是通用的。我不认为无法执行这种强制性是有原因的,但是是 Rust has some issues in this area
Rust理解的最直接的解决方法是使用闭包:
let _ : fn(&Path) -> io::Result<()> = |p| fs::remove_file(p);

关于rust - 如何将泛型函数转换为带有引用参数的函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63234541/

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