Cargo构建报错:DBus接口impl中不能定义无self的new函数
问题原因
#[dbus_interface] 宏标记的 impl 块是用来定义DBus接口方法的,这类方法必须是实例方法(第一个参数必须是 &self、&mut self 或 self),而你定义的 new() 是关联函数(没有 self 参数),不符合这个宏的要求,所以编译报错。
解决方法
把 new() 关联函数移到不带 #[dbus_interface] 标注的独立 impl 块中,带宏的 impl 块只放需要暴露给 DBus 的实例方法。
修改后的代码示例:
pub struct Service { start: Event, collections: Vec<Collection>, clients: Vec<Client>, } // 普通impl块:专门放关联函数(如new)和非DBus接口的方法 impl Service { pub async fn new() -> Self { Service { start: event_listener::Event::new(), collections: Vec::new(), clients: Vec::new(), } } } // 带dbus_interface宏的impl块:仅存放DBus接口要求的实例方法 #[dbus_interface(name ="org.freedesktop.Secret.Service")] impl Service { // 这里写所有需要暴露给DBus的实例方法,比如: // pub async fn your_dbus_method(&self) -> Result<(), Box<dyn Error>> { // // 方法实现 // } }
这样拆分后,new() 作为普通的关联函数可以正常编译,带宏的 impl 块也符合 DBus 接口方法的要求。
内容的提问来源于stack exchange,提问作者a001
相关产品推荐
相关产品推荐

