因此,目标类型为:

pub type SkittleModuleCommand = fn(ctx: Context, msg: Message, args: Vec<String>) -> dyn Future<Output = Result<()>>

但是rust编译器指出,im试图作为参数传递的函数的类型不正确. 错误:

error[E0308]: mismatched types
  --> src/lib.rs:17:37
   |
17 |     module.register_command("ping", ping);
   |            ----------------         ^^^^ expected fn pointer, found fn item
   |            |
   |            arguments to this method are incorrect
   |
   = note: expected fn pointer `fn(serenity::prelude::Context, serenity::model::channel::Message, Vec<_>) -> (dyn std::future::Future<Output = Result<(), anyhow::Error>> + 'static)`
                 found fn item `fn(serenity::prelude::Context, serenity::model::channel::Message, Vec<_>) -> impl std::future::Future<Output = Result<(), anyhow::Error>> {commands::ping::exec}`
   = note: when the arguments and return types match, functions can be coerced to function pointers
note: method defined here
  --> /home/mcorange/@Projects/rust/autistic-bot/src/lib.rs:62:12
   |
62 |     pub fn register_command(&mut self, name: &str, comm: SkittleModuleCommand) {
   |            ^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0308`.
warning: `skittle-bot-core-module` (lib) generated 4 warnings

整个项目都在github美元.

此外,以下是可重现的最小示例:

use std::{future::Future, collections::HashMap};


pub type SkittleModuleCommand = fn(a: usize) -> dyn Future<Output = ()>;

pub async fn module_fn(a: usize) {}

fn main() {
    let mut mod_hm: HashMap<String, SkittleModuleCommand> = HashMap::new();

    mod_hm.insert(String::from(""), module_fn);

}

我试着使用变形,但我不能得到错误的类型正确.

谢谢你的帮助!

推荐答案

-> dyn Future<Output = Result<()>>

返回一个原始的dyn通常是没有意义的,它是a DST,当不在指针后面时,这是非常困难的.

此外,正如错误消息告诉您的那样,您正在try 返回impl Future,这是完全不同的事情(它是实现特征的特定但不透明的类型).

您需要做的是:

  1. 更改您的类型,使dyn FutureBox中,这实际上将允许您操作并返回1

    fn(ctx: Context, msg: Message, args: Vec<String>) -> Box<dyn Future<Output = Result<()>>>;
    
  2. 从您的函数返回它,我实际上不确定是否可以直接使用内置语法或futures模块(其他人可能知道),但您可以只对您的异步函数进行go 糖化:

    pub fn exec(ctx: Context, msg: Message, _: Vec<String>) -> Box<dyn Future<Output = Result<()>>> {
        Box::new(async move {
            msg.reply_mention(ctx, "Pong!").await?;
            Ok(())
        })
    }
    

我试着使用变形,但我不能得到错误的类型正确.

对于编译错误,这从来都不是正确的解决方案,尤其是当您随意地向墙上扔屎的时候.

Rust相关问答推荐

计算具有相邻调换且没有插入或删除的序列的距离

如何找到一个数字在二维数组中的位置(S)?

如何在Rust中表示仅具有特定大小的数组

rust 迹-内存管理-POP所有权-链表

在UdpSocket上使用sendto时的隐式套接字绑定

这是不是在不造成嵌套的情况下从枚举中取出想要的变体的惯用方法?

捕获FnMut闭包的时间不够长

正则表达式中的重叠匹配?(铁 rust 正则式发动机)

在文件链实施中绕过borrow 判断器

为什么Rust不支持带关联常量的特征对象?

在Rust内联程序集中使用字符串常量

Rust面向对象设计模式

如何从宏调用闭包?

如何限制 GtkColumnView 行数

使用 Rust 从 Raspberry Pi Pico 上的 SPI 读取值

从嵌入式 Rust 中的某个时刻开始经过的时间

n 个范围的笛卡尔积

`use std::error::Error` 声明中断编译

如何在 Rust 中编写涉及异步的重试函数

在 Rust 中退出进程