是否可以将Closure / Function作为结构的成员?(Is it possible to have a Closure/Function as a member of a struct?)

编程入门 行业动态 更新时间:2024-10-26 18:21:48
是否可以将Closure / Function作为结构的成员?(Is it possible to have a Closure/Function as a member of a struct?) 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,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} } }

Why do I get this error? I also want Foo to work with normal functions and closures.

I know that there was a closure reform in the past, so what would be the correct signature for f so that Foo works with closures and functions?

最满意答案

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

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} } }

有关这方面的更多信息,您可以阅读此博客文章 ,其中包含此案例。 以下是博客文章中的相关部分:

将指定边界的两种情况是(1)将闭包放入结构中,其中必须明确命名所有生命周期,以及(2)指定数据并行API。 在第一种情况下,一个包含闭包的结构定义,你希望写下面的东西...

If you place a closure inside of a struct you need to explicitly name the lifetime.

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} } }

For more information on that you can read this blog post which coveres this case. Here is the relevant part from the 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 ...

更多推荐

本文发布于:2023-08-07 04:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1460051.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:成员   结构   Function   Closure   member

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!