gpt4 book ai didi

rust - 是否可以将闭包/函数作为结构的成员?

转载 作者:行者123 更新时间:2023-11-29 08:00:06 25 4
gpt4 key购买 nike

struct Foo<A,B>{
f: |A| -> B // err: Missing life time specifier
}
impl<A,B> Foo<A,B>{
fn new(f: |A| -> B) -> Foo<A,B>{
Foo {f:f}
}
}

为什么会出现此错误?我还希望 Foo 可以使用正常的函数和闭包。

我知道过去曾进行过闭包改革,那么 f 的正确签名是什么才能使 Foo 与闭包和函数一起工作?

最佳答案

如果在结构中放置一个闭包,则需要明确命名生命周期。

struct Foo<'a,A,B>{
f: |A|:'a -> B
}

impl<'a,A,B> Foo<'a,A,B>{
fn new(f: |A| -> B) -> Foo<A,B>{
Foo {f:f}
}
}

有关这方面的更多信息,您可以阅读 this blog post其中涵盖了这种情况。以下是博文的相关部分:

The two cases where bounds would be specified are (1) placing closures into a struct, where all lifetimes must be explicitly named and (2) specifying data-parallel APIs. In the first case, a struct definition that contains a closure, you would expect to write something like the following ...

关于rust - 是否可以将闭包/函数作为结构的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25193270/

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