我对如何使它正常工作有些困惑,我已经从真实的东西中删除了它。我写了一个特质:
pub trait Renderable<F: Fn(&PropertyTags)> {
fn set_property_changed_callback(&mut self, callback: Option<F>);
}
的“子级”参数受其add_child
限制并且PropertyTags
仅仅是一个枚举。我提供了的类型的模拟实现child
来演示我的用法:
pub struct Child<F: Fn(&PropertyTags)> {
property_changed_callback: Option<F>,
}
impl<F: Fn(&PropertyTags)> Renderable<F> for Child<F> {
fn set_property_changed_callback(&mut self, callback: Option<F>) {
self.property_changed_callback = callback;
}
}
然后这些将用作:
pub fn add_child<REND, C>(&mut self, child: &mut REND)
where C: Fn(&PropertyTags),
REND: Renderable<C>
{
let tc = Some(|property_tag: &PropertyTags|{
});
child.set_property_changed_callback(tc);
}
我收到错误消息:
child.set_property_changed_callback(tc);
| ^^ expected type parameter, found closure
|
= note: expected type `std::option::Option<C>`
= note: found type `std::option::Option<[closure@src/rendering/mod.rs:74:31: 76:18]>`
= help: here are some functions which might fulfill your needs:
- .take()
- .unwrap()
我设置了一个最小的游乐场示例,在此处重现了问题:https : //play.rust-lang.org/?gist=bcc8d67f25ac620fe062032d8737954b&version=stable&backtrace=0
问题是add_child
声称接受any Renderable<C>
,whereC
可以是实现的任何类型Fn(&PropertyTags)
,但是函数试图给它一个特定的闭包类型,该类型可能与C
。
为了使它起作用,add_child
的签名应如下所示:
pub fn add_child<REND>(&mut self, child: &mut REND)
where REND: Renderable<AddChildCallback>
AddChildCallback
具体类型的名称在哪里(实现Fn(&PropertyTags)
)。
这里的困难在于,一方面,闭包类型没有可在Rust代码中使用的名称,另一方面,Fn
手动实现是不稳定的,因此需要每晚进行编译。
我还将注意到,通过将回调类型设置为类型参数,Renderable
在设置了第一个回调之后,不能为分配其他类型的回调,因为第一个回调将确定的具体类型Renderable
。这可能适合您的用法,我只是想确保您知道这一点。
如果您想要一个适用于稳定编译器(从Rust 1.14.0开始)的解决方案,则必须对回调进行包装。add_child
的签名如下所示:
pub fn add_child<REND>(&mut self, child: &mut REND)
where REND: Renderable<Box<Fn(&PropertyTags)>>
这是更新的游乐场链接,其中包含的示例实现Fn
。注意,对于这些参数call
,call_mut
并call_once
作为一个元组传递,如通过特征定义要求。为了完整起见,以下代码被复制:
struct RenderableCallback {
}
impl<'a> Fn<(&'a PropertyTags,)> for RenderableCallback {
extern "rust-call" fn call(&self, args: (&'a PropertyTags,)) -> Self::Output {
}
}
impl<'a> FnMut<(&'a PropertyTags,)> for RenderableCallback {
extern "rust-call" fn call_mut(&mut self, args: (&'a PropertyTags,)) -> Self::Output {
}
}
impl<'a> FnOnce<(&'a PropertyTags,)> for RenderableCallback {
type Output = ();
extern "rust-call" fn call_once(self, args: (&'a PropertyTags,)) -> Self::Output {
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句