V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
gramyang
V2EX  ›  Rust

rust 如何实现闭包 Vec?

  •  
  •   gramyang · 2020-05-19 21:30:23 +08:00 · 2468 次点击
    这是一个创建于 1409 天前的主题,其中的信息可能已经有所发展或是发生改变。
    函数指针 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-05-20 13:31:07 +08:00
    修改了一下终于可行了,代码:
    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-05-19 22:32:07 +08:00 via Android
    用 Box<dyn T>
    gwy15
        2
    gwy15  
       2020-05-19 22:46:04 +08:00
    gramyang
        3
    gramyang  
    OP
       2020-05-20 13:29:10 +08:00
    @sosilver 可行!
    sosilver
        4
    sosilver  
       2020-05-20 14:38:47 +08:00 via Android
    @gwy15 这样写只能装一个 closure 。因为不同的 closure 的类型是不同的,Vec<T>的推导类型由第一个放进去的决定,然后就放不进去其它的了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3762 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 00:14 · PVG 08:14 · LAX 17:14 · JFK 20:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.