在下面的代码中:
use std::env;
use serenity::{
async_trait,
model::{channel::Message, gateway::Ready},
prelude::*,
utils::MessageBuilder,
};
struct Handler;
use serenity::model::id::GuildId;
use serenity::model::voice::VoiceState;
#[async_trait]
impl EventHandler for Handler {
async fn voice_state_update(&self, context: Context, arg2 : Option<GuildId>, old : Option<VoiceState>, new : VoiceState) {
//async fn voice_state_update(&self, context: Context, arg2 : Option<GuildId>, new : VoiceState) {
}
}
#[tokio::main]
async fn main() {
// Configure the client with your Discord bot token in the environment.
let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment");
let mut client =
Client::builder(&token).event_handler(Handler).await.expect("Err creating client");
if let Err(why) = client.start().await {
println!("Client error: {:?}", why);
}
}
Run Code Online (Sandbox Code Playgroud)
产生以下错误:
错误[E0050]:方法
voice_state_update有5个参数,但特征中的声明voice_state_update有4个 --> src/main.rs:18:33 | 18 | 18 async fn voice_state_update(&self, context: Context, arg2 : Option, old : Option, new : VoiceState) { |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 预期 4 个参数,找到 5 个
然而这却是出乎意料的。根据文档 https://docs.rs/serenity/0.10.9/src/serenity/client/event_handler.rs.html#400-407和https://github.com/serenity-rs/serenity/blob /a576cc0fd158a29e238ec15034d3919c3b26dbab/src/client/event_handler.rs#L400这个方法定义了5个参数?
但是,如果我删除该old : Option<VoiceState>参数,那么它会成功编译。如何解释这种行为?
我的cargo.lock文件包含:
...
[[package]]
name = "serenity"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6275d443266aedf2be507a245ddc23db0c07b1b99774e16f3c879e96a78b067a"
...
Run Code Online (Sandbox Code Playgroud)
您基本上链接到答案 \xe2\x80\x93 函数定义标记为#[cfg(feature = "cache")],因此它仅在cache启用该功能时适用。
#[cfg(feature = "cache")]\nasync fn voice_state_update(\n &self,\n _ctx: Context,\n _: Option<GuildId>,\n _old: Option<VoiceState>,\n _new: VoiceState,\n) {\n}\nRun Code Online (Sandbox Code Playgroud)\n当该功能被禁用时,还有另一个适用的功能定义。
\n#[cfg(not(feature = "cache"))]\nasync fn voice_state_update(&self, _ctx: Context, _: Option<GuildId>, _: VoiceState) {}\nRun Code Online (Sandbox Code Playgroud)\n显然,文档是在启用该功能的情况下构建的,但您使用的包没有该功能。
\n请注意,这是一个展示如何不使用功能的示例。这种方法不仅令人困惑 \xe2\x80\x93 它在某些方面完全被破坏了。具体来说,如果一个 crate 版本在依赖图中多次使用,Cargo 将合并在该 crate 的所有使用中启用的所有功能。因此,如果一个 crate 依赖于serenity没有该cache功能,而另一个 crate 启用了该功能,Cargo 将为它们都启用该功能,并且只编译该 crate 一次,因此依赖于该功能的 crateserenity将停止编译。