函数指针 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
求大佬指点。
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
}
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
}