< 返回版块

ziyouwa 发表于 2021-07-30 11:21

初初级萌新,学习到闭包作为输出时,遇到如下问题:

fn  create_fn(arg1: i32) -> impl Fn() -> i32 {
  move || arg1
}

fn main() {
  let a = 12;
  let myfn = create_fn(a);

  println!("result is {}",myfn());
}

上面的代码是没问题的。但是当我向把arg1改成&str这样的非标量类型时,就涉及到生命周期的问题,试了很多次都不对,不知道具体改怎么写。

评论区

写评论
htqx 2021-07-31 14:47

fn  create_fn<'a>(arg1: &'a i32) -> impl Fn() -> &'a i32 {
  move || arg1
}

fn main() {
  let a = 12;
  let myfn = create_fn(&a);

  println!("result is {}",myfn());
}

作者 ziyouwa 2021-07-30 13:11

验证通过,谢谢!

--
👇
Bai-Jinlin: ```rust fn create_fn<'a>(arg1: &'a str) -> impl Fn() -> &'a str { move || arg1 } fn main() { let a = "S".to_string(); let b = create_fn(&a); let c = b(); assert_eq!(c, "S"); }

Bai-Jinlin 2021-07-30 11:48
fn create_fn<'a>(arg1: &'a str) -> impl Fn() -> &'a str {
    move || arg1
}
fn main() {
    let a = "S".to_string();
    let b = create_fn(&a);
    let c = b();
    assert_eq!(c, "S");
}
1 共 3 条评论, 1 页