这是我的示例代码。我正在尝试将a传递Vec<T>
给其中的函数T: Into<_>
!
enum Test {
FN(Box<dyn Fn()>),
STR(String),
}
impl<F> From<F> for Test
where F: Fn() + 'static
{
fn from(f: F) -> Self {
Self::FN(Box::new(f))
}
}
impl From<String> for Test {
fn from(s: String) -> Self {
Self::STR(s)
}
}
fn main() {
into(vec![
|| println!("func 1"),
|| println!("func 2"),
String::from("string 1"),
]);
}
fn into<T>(v: Vec<T>)
where T: Into<Test>
{
for test in v {
let test = test.into();
match test {
Test::FN(func) => func(),
Test::STR(s) => println!("{}", s),
}
}
}
错误发生在第二次关闭时:
expected closure, found a different closure
问题在于Into <_>不能调整为动态,因为它是Sized,所以不起作用!
我希望输出:
func 1
func 2
string 1
有任何答案或想法吗?
感谢您提供所有答案,我通过创建自己的MyInto
特征找到了自己的解决方案:
trait MyInto {
fn my_into(&self) -> Test;
}
enum Test<'l> {
FN(&'l dyn Fn()),
STR(String),
}
impl<F> MyInto for F
where F: Fn() + 'static
{
fn my_into(&self) -> Test {
Test::FN(self)
}
}
impl MyInto for String {
fn my_into(&self) -> Test {
Test::STR(self.to_owned())
}
}
fn main() {
into(vec![
&|| println!("func 1"),
&|| println!("func 2"),
&String::from("string 1"),
]);
}
fn into(v: Vec<&dyn MyInto>) {
for test in v {
let test = test.my_into();
match test {
Test::FN(func) => func(),
Test::STR(s) => println!("{}", s),
}
}
}
现在的输出是:
func 1
func 2
string 1
现在可以使用dyn
in &dyn MyInto
,因为MyInto
不是Sized
!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句