简体   繁体   English

如何在 Rust 中将类型参数指定为函数参数?

[英]How do I specify type parameters as being function arguments in Rust?

I'm trying to make a list that will hold Box<dyn Fn(&E)> where E is specified as part of the type.我正在尝试制作一个包含Box<dyn Fn(&E)> ,其中E被指定为类型的一部分。 This works until E contains a reference, at which point it starts asking for lifetimes that aren't relevant.这一直有效,直到E包含一个引用,此时它开始询问不相关的生命周期。

A simpler example:一个更简单的例子:

pub struct CallbackTest<E> {
    pub cb: Box<dyn Fn(&E)>,
}

impl<E> CallbackTest<E> {
    pub fn new<F>(cb: F) -> Self
    where
        F: Fn(&E)
    {
        Self { cb: Box::new(cb) }
    }
}

pub struct GameData { /* ... */ }

pub type TestRef = CallbackTest<(u32, &GameData)>;

This gives me a missing lifetime specifier error.这给了我一个missing lifetime specifier错误。 I could put a lifetime parameter on TestRef to make it work, but that's not the correct lifetime.可以TestRef上放置一个生命周期参数以使其工作,但这不是正确的生命周期。 I don't want the &GameData to have to live for the entire lifetime of the CallbackTest , just during the function call.我不希望&GameDataCallbackTest的整个生命周期中都存在,只是在函数调用期间。

EDIT: The &GameData is intentional.编辑: &GameData 是故意的。 It's not a mistake.这不是一个错误。 I hope my changes have made the goal behind this more obvious.我希望我的改变使这背后的目标更加明显。

Any advice?有什么建议吗?

Here we are rust.playground我们在这里rust.playground

use std::marker::PhantomData;

pub struct CallbackTest<'a, E, Fa: 'a + Fn(&E)> {
    pub cb: Box<Fa>,
    _e: &'a PhantomData<E>,
}

impl<'a, E, Fa: 'a + Fn(&E)> CallbackTest<'a, E, Fa> {
    pub fn new(cb: Fa) -> Self
    {
        Self { 
            cb: Box::new(cb), 
            _e: &PhantomData
        }
    }
}

pub struct GameData { 
    pub field: i32,
}

pub type TestRef<'a, 'b, Fb> = CallbackTest<'b, (u32, &'a GameData, ), Fb>;

fn main() {
    let game_data = GameData{ field: 42};
    let test_ref: TestRef<_> = CallbackTest::new(|(val, gd): &(u32, &GameData)| { println!("val:{}, field:{}", val, (*gd).field)});
    (test_ref.cb)(&(24, &game_data));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM