gramyang
V2EX  ›  Rust

rust 如何实现闭包 Vec?

By gramyang at 2020 年 5 月 19 日 · 3928 次点击
函数指针 Vec 是可以实现的,但是不知道如何实现闭包 Vec 。

type Bibao = dyn Fn(String)->String + 'static;

pub fn close_test4(){
let a = "456";
let b1: Bibao = move |mut s:String|{
s.push_str(a);
s
};
let mut v = Vec::new();
op1(b1,&v);
v.get(0)(String::from("123"));
}

fn op1<T:Fn(String) ->String>(t:T,mut v:&Vec<T>){
v.push(t);
}

报错:expected trait object `dyn std::ops::Fn`, found closure

求大佬指点。
第 1 条附言  ·  2020 年 5 月 20 日
修改了一下终于可行了,代码:
type Boo = Box<dyn Fn(i32) -> String>;

fn op1(x:i32, y:String) -> impl Fn(i32) -> String {
move |s:i32| {
let mut a = String::new();
a.push_str((x+s).to_string().as_str());
a.push_str(y.as_str());
a
}
}

fn op2(x:i32) -> impl Fn(i32) -> String{
move |s:i32| {
let mut a = String::new();
a.push_str((x+s).to_string().as_str());
a
}
}

fn op3(y:String) ->impl Fn(i32) -> String{
move |s:i32| {
let mut a = String::new();
a.push_str((s).to_string().as_str());
a.push_str(y.as_str());
a
}
}

pub fn c_t5(){
let c1 = Box::new(op1(10,String::from("ab")));
let c2 = Box::new(op2(20));
let c3 = Box::new(op3(String::from("cd")));
let mut vec:Vec<Boo> = Vec::new();
vec.push(c1);
vec.push(c2);
vec.push(c3);
println!("{} {} {}",vec.get(0).unwrap()(30),vec.get(1).unwrap()(30),
vec.get(2).unwrap()(30));//40ab 50 30cd
}
4 条回复  •  2020-05-20 14:38:47 +08:00
sosilver
   1
sosilver  
   2020 年 5 月 19 日 via Android
用 Box<dyn T>
gwy15
   2
gwy15  
   2020 年 5 月 19 日
gramyang
   3
gramyang  
OP
   2020 年 5 月 20 日
@sosilver 可行!
sosilver
   4
sosilver  
   2020 年 5 月 20 日 via Android
@gwy15 这样写只能装一个 closure 。因为不同的 closure 的类型是不同的,Vec<T>的推导类型由第一个放进去的决定,然后就放不进去其它的了。
© 2026 V2EX · 24ms · 3.9.8.5