gpt4 book ai didi

generics - 将函数作为参数传递时,如何遵守生命周期限制?

转载 作者:行者123 更新时间:2023-12-03 11:43:14 24 4
gpt4 key购买 nike

原始发行

这段代码与我要修复的代码相对相似。我也在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

最佳答案

查看第一个函数参数:

f1: impl Fn(&str) -> Result<(&str, A), ()>,
A类型的值从何而来?它必须是:

从参数中的 str或派生的
  • 无处可摘,这意味着它是'static

  • 但是 A是为 foo声明的,而不是为特定的 f1参数声明的。这意味着 A的生存期不能取决于 f1的参数。但这正是 barbaz所做的。

    所以,你可以做什么?考虑到“假定无法修改此功能”的要求,您将不得不更改 barbaz,以便 A的类型为静态。这使您可以选择新分配的 String&'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的类型签名表示输入 &str的生存期与结果中的 &A之间的关联。

    关于generics - 将函数作为参数传递时,如何遵守生命周期限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61627860/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com