【问题标题】:How do I comply with lifetime bounds when passing functions as argument?将函数作为参数传递时如何遵守生命周期?
【发布时间】:2020-05-06 05:15:36
【问题描述】:

原始问题

这段代码与我试图修复的那段代码比较相似。我也在Rust user's forum 上问过这个问题。

playground

/// assume this function can't be modified.
fn foo<A>(
    f1: impl Fn(&str) -> Result<(&str, A), ()>,
    base: &str,
    f2: impl Fn(A) -> bool
) {
    let s: String = base.to_owned();
    let option = Some(s.as_ref());
    let mapped = option.map(f1);
    let r = mapped.unwrap();
    let (rem, prod) = r.unwrap();
    assert!(f2(prod));
    assert_eq!(rem.len(), 0);
}


fn main() {
    fn bar<'a>(s: &'a str) -> Result<(&'a str, &'a str), ()> {
        Ok((&s[..1], &s[..]))
    }


    fn baz(s: &str) -> Result<(&str, &str), ()> {
        Ok((&s[..1], &s[..]))
    }

    foo(bar, "string", |s| s.len() == 5); // fails to compile

    foo(baz, "string", |s| s.len() == 5); // fails to compile 
}
error[E0271]: type mismatch resolving `for<'r> <for<'a> fn(&'a str) -> std::result::Result<(&'a str, &'a str), ()> {main::bar} as std::ops::FnOnce<(&'r str,)>>::Output == std::result::Result<(&'r str, _), ()>`
  --> src/main.rs:27:5
   |
2  | fn foo<A>(
   |    ---
3  |     f1: impl Fn(&str) -> Result<(&str, A), ()>,
   |                          --------------------- required by this bound in `foo`
...
27 |     foo(bar, "string", |s| s.len() == 5); // fails to compile
   |     ^^^ expected bound lifetime parameter, found concrete lifetime

编辑:

根据这里的许多人、internals thread I made 和 rust 用户论坛上的建议,我更改了我的代码以通过使用包装器特征来简化它。

playground


trait Parser<'s> {
    type Output;

    fn call(&self, input: &'s str) -> (&'s str, Self::Output);
}

impl<'s, F, T> Parser<'s> for F
where F: Fn(&'s str) -> (&'s str, T) {
    type Output = T;
    fn call(&self, input: &'s str) -> (&'s str, T) {
        self(input)
    }
}

fn foo<F1, F2>(
    f1: F1,
    base: &'static str,
    f2: F2
) 
where 
    F1: for<'a> Parser<'a>,
    F2: FnOnce(&<F1 as Parser>::Output) -> bool
{
    // These two lines cannot be changed.
    let s: String = base.to_owned();
    let str_ref = s.as_ref();

    let (remaining, produced) = f1.call(str_ref);
    assert!(f2(&produced));
    assert_eq!(remaining.len(), 0);
}

struct Wrapper<'a>(&'a str);

fn main() {
    fn bar<'a>(s: &'a str) -> (&'a str, &'a str) {
        (&s[..1], &s[..])
    }

    fn baz<'a>(s: &'a str) -> (&'a str, Wrapper<'a>) {
        (&s[..1], Wrapper(&s[..]))
    }

    foo(bar, "string", |s| s.len() == 5); // fails to compile

    foo(baz, "string", |s| s.0.len() == 5); // fails to compile 
}

此代码当前生成内部编译器错误:

error: internal compiler error: src/librustc_infer/traits/codegen/mod.rs:61: Encountered error `OutputTypeParameterMismatch(Binder(<[closure@src/main.rs:45:24: 45:40] as std::ops::FnOnce<(&<for<'a> fn(&'a str) -> (&'a str, &'a str) {main::bar} as Parser<'_>>::Output,)>>), Binder(<[closure@src/main.rs:45:24: 45:40] as std::ops::FnOnce<(&&str,)>>), Sorts(ExpectedFound { expected: &str, found: <for<'a> fn(&'a str) -> (&'a str, &'a str) {main::bar} as Parser<'_>>::Output }))` selecting `Binder(<[closure@src/main.rs:45:24: 45:40] as std::ops::FnOnce<(&&str,)>>)` during codegen

thread 'rustc' panicked at 'Box<Any>', src/librustc_errors/lib.rs:875:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

note: the compiler unexpectedly panicked. this is a bug.

note: we would appreciate a bug report: https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.md#bug-reports

note: rustc 1.43.0 (4fb7144ed 2020-04-20) running on x86_64-unknown-linux-gnu

note: compiler flags: -C codegen-units=1 -C debuginfo=2 --crate-type bin

note: some of the compiler flags provided by cargo are hidden

error: aborting due to previous error

error: could not compile `playground`.

To learn more, run the command again with --verbose.

我已经提交了错误报告here

【问题讨论】:

  • 您能否更详细地描述预期的行为和问题是什么?很高兴您提供了一个 Playground 链接,但我们不应该运行 Playground 来猜测您在问什么。
  • Fn trait 似乎不够灵活,无法表达这一点,因此您应该定义自己的 trait。
  • 我刚刚在操场上看到了“假设这个函数不能被修改”的评论。在这种情况下,该函数根本无法获取您想要传入的函数。A 需要具有静态生命周期,因此使其成为某种“拥有”类型(在本例中为 String)。跨度>
  • @PeterHall 好的,那么假设可以修改该功能,您会进行哪些修改?
  • @AntoniaCalia-Bogan 我在下面的回答中有一个建议。但是我们在这里讨论的是泛型函数,因此它实际上取决于您对泛型的预期界限。

标签: generics rust lifetime borrowing


【解决方案1】:

查看第一个函数参数:

f1: impl Fn(&str) -> Result<(&str, A), ()>,

A 类型的值从何而来?它必须是:

  • 派生自参数中的str,或
  • 不知从何而来,这意味着它是'static

但是A 是为foo 声明的,而不是为特定的f1 参数声明的。这意味着A 的生命周期不能依赖于f1 的参数。但这正是 barbaz 所做的。

那你能做什么?鉴于您要求“假设无法修改此功能”,您不得不更改 barbaz 以便 A 的类型是静态的。这使您可以选择新分配的String&amp;'static str

fn bar<'a>(s: &'a str) -> Result<(&'a str, String), ()> {
    Ok((&s[..1], s[..].to_owned()))
}

或者:

fn bar<'a>(s: &'a str) -> Result<(&'a str, &'static str), ()> {
    Ok((&s[..1], "hello"))
}

如果您能够更改 foo 的类型签名,则可以在参数函数的签名中使用对 A 的引用,这样您就可以描述它们的生命周期,并与它们的关联其他论点:

例如:

fn foo<A: ?Sized>(
    f1: impl Fn(&str) -> Result<(&str, &A), ()>,
    base: &str,
    f2: impl Fn(&A) -> bool
) {
    unimplemented!()
}

这相当于以下内容,没有生命周期省略:

fn foo<A: ?Sized>(
    f1: impl for<'a> Fn(&'a str) -> Result<(&'a str, &'a A), ()>,
    base: &str,
    f2: impl for<'a> Fn(&'a A) -> bool
) {
    unimplemented!()
}

请注意,f1 的类型签名现在表示输入 &amp;str 的生命周期与结果中的 &amp;A 之间的关联。

【讨论】:

    【解决方案2】:

    对于以后阅读本文并想知道我是否找到解决方法的任何人,我做到了!

    此解决方法涉及将函数调用引用的状态放入Context 结构中。由于较高等级特征边界 (HRTB) 的当前问题,此解决方法完全避免了它们。相反,我们将对象初始化(这可能很昂贵)重构到 Context 的构造函数中。上下文完全拥有函数状态。不过这很好,因为该函数只需要对该状态的引用,而不是所有权。每当我们需要调用函数时,我们将其传递给 Context 的调用函数,以确保函数参数的生命周期及其输出与其运行所在的上下文的生命周期相匹配。

    playground

    // Workaround code: the state of the function is placed 
    // into a struct so that all of the references are valid
    // for the lifetime of of &self. This way concrete lifetimes
    // can be used because all lifetimes start on the function 
    // call, rather than several statements into the function. 
    //
    // This work around eliminates the need for Higher Ranked 
    // Trait Bounds (HRTBs), since all lifetimes are instantiated
    // on function initialization.
    
    struct Wrapper<'a>(&'a str);
    
    struct ParserContext {
        inner: String
    }
    
    impl ParserContext {
        fn new(base: &str) -> Self {Self {inner: base.to_owned()}}
    
        fn call<'a, O>(
            &'a self, 
            f1: fn(&'a str) -> (&'a str, O),
            f2: fn(O) -> bool,
        ) {
            let (remaining, produced) = f1(self.inner.as_str());
            assert_eq!(remaining.len(), 0);
            assert!(f2(produced));
        }
    }
    
    
    fn main() {
        fn bar(s: &str) -> (&str, &str) {
            (&s[..0], &s[..])
        }
    
        fn baz(s: &str) -> (&str, Wrapper) {
            (&s[..0], Wrapper(&s[..]))
        }
    
    
        // I tried to extract the section below into its
        // own function previously (foo) but this would
        // always inevitably fail because of lifetime issues.
        // this work around only adds one line of code to the calling
        // function to create the context to hold the state 
        // used by the functions passed to `call`, so this 
        // is an acceptable, and rather eloquent work around.
        let pc = ParserContext::new("string");
    
        pc.call(bar, |s| s.len() == 6);
        pc.call(baz, |s| s.0.len() == 6);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 2015-12-08
      • 2018-06-15
      • 1970-01-01
      • 2014-06-29
      相关资源
      最近更新 更多