首页 > 解决方案 > 如何将额外的参数传递给 Rust 中的“Fn”参数?

问题描述

要使用名为 Teloxide 的 TG bot crate 处理命令,我必须提供一个handle_command具有特殊签名的函数:

pub async fn commands_repl<R, Cmd, H, Fut, HandlerE, N>(requester: R, bot_name: N, handler: H)
where
    Cmd: BotCommand + Send + 'static,
    H: Fn(UpdateWithCx<R, Message>, Cmd) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<(), HandlerE>> + Send + 'static,
    Result<(), HandlerE>: OnError<HandlerE>,
    HandlerE: Debug + Send,
    N: Into<String> + Send + 'static,
    R: Requester + Send + Clone + 'static,
    <R as Requester>::GetUpdatesFaultTolerant: Send,

然而,在我的handler函数体中,我想访问 Tokio Sender 通道来发送从我的电报消息中接收到的数据。

所以在代码中,这就是我想做的:

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let (tx, rx) = mpsc::channel(1);
    let bot = Bot::new(&cfg.telegram.api_key).auto_send();
    let bot_name: String = String::from("Tracker Bot");
    teloxide::commands_repl(bot, bot_name, handle_command).await;

    Ok(())
}

async fn handle_command(
    cx: UpdateWithCx<AutoSend<Bot>, Message>,
    command: telegram::Command,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    match command {
        telegram::Command::Help => cx.answer(telegram::Command::descriptions()).await?,
        telegram::Command::AddToken(token) => {
            let addr: H160 = token.parse()?;
            tx.send(addr).await?;
            cx.answer(format!("Token added: {}", token)).await?
        }
    };

    Ok(())
}

解决此问题的最佳方法是什么?我考虑过制作Sender一个全局变量,但这似乎会产生很多其他问题。那么还有其他方法可以访问handle_command函数内的该变量吗?

标签: rustrust-tokio

解决方案


推荐阅读