Rust中FindAppointmentsAsync的&self参数传入及AppointmentStore初始化问题
问题:Rust中使用windows crate的FindAppointmentsAsync时,如何正确获取AppointmentStore实例?
我是Rust新手,正在使用windows crate,但不清楚FindAppointmentsAsync函数中的&self参数应如何设置。以下是我的项目配置和代码:
Cargo.toml
[package] name = "rust-test" version = "0.1.0" edition = "2021" [dependencies] [dependencies.windows] version = "0.43.0" features = [ "ApplicationModel", "ApplicationModel_Appointments", "Foundation_Collections", ]
main.rs
use std::time::Duration; use windows::{ core::*, ApplicationModel::Appointments::*, Foundation::{DateTime, TimeSpan}, }; fn main() -> Result<()> { let rangestart = DateTime::default(); let rangelength = TimeSpan::from(Duration::new(60 * 60 * 24 * 30, 0)); println!("test"); unsafe { let store = AppointmentStore(); let result = AppointmentStore::FindAppointmentsAsync(&store, rangestart, rangelength); } Ok(()) }
我尝试了几种初始化AppointmentStore的方式,但均出现错误:
- 使用
let store = AppointmentStore::new();时,报错:no function or associated item named 'new' found - 使用
let store = AppointmentStore();时,报错:expected 1 argument, found 0 - 使用
let store = AppointmentStore("");时,报错:cannot initialize a tuple struct which contains private fields
解决方案
Windows Runtime API中,AppointmentStore不能直接实例化,必须通过AppointmentManager::RequestStoreAsync异步方法获取——这是因为访问日历存储需要系统权限,该方法会处理权限申请并返回合法的存储实例。
修改后的完整代码
use std::time::Duration; use windows::{ core::*, ApplicationModel::Appointments::*, Foundation::{DateTime, TimeSpan}, }; #[tokio::main] async fn main() -> Result<()> { let rangestart = DateTime::default(); let rangelength = TimeSpan::from(Duration::new(60 * 60 * 24 * 30, 0)); // 异步请求日历存储实例,指定访问权限 let store = AppointmentManager::RequestStoreAsync(AppointmentStoreAccessType::AllCalendarsReadWrite) .await?; // 调用实例方法FindAppointmentsAsync,无需手动传递&self let appointments = store.FindAppointmentsAsync(rangestart, rangelength) .await?; println!("找到{}个预约", appointments.Size()?); Ok(()) }
更新后的Cargo.toml
需要添加异步运行时依赖和Windows异步API的feature:
[package] name = "rust-test" version = "0.1.0" edition = "2021" [dependencies] tokio = { version = "1.0", features = ["full"] } [dependencies.windows] version = "0.43.0" features = [ "ApplicationModel", "ApplicationModel_Appointments", "Foundation_Collections", "Foundation_Async", ]
关键细节说明
- 实例获取逻辑:
RequestStoreAsync是获取AppointmentStore的唯一合法途径,需传入AppointmentStoreAccessType枚举指定权限等级(如AllCalendarsReadWrite表示读写所有日历)。 - 异步处理:Windows Runtime API多为异步设计,需用
async/await配合异步运行时(如tokio)处理结果。 - 方法调用方式:
FindAppointmentsAsync是AppointmentStore的实例方法,获取到实例后直接通过store.FindAppointmentsAsync(...)调用即可,Rust会自动处理&self的传递。
内容的提问来源于stack exchange,提问作者Topaz Rindu Nabiyallah
相关产品推荐
相关产品推荐

