如何创建未装箱的函数/闭包数组? [英] How do I create an array of unboxed functions / closures?

查看:56
本文介绍了如何创建未装箱的函数/闭包数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编者注:这个问题是在Rust 1.0之前问的,此后一些语法已更改,但基本概念仍然存在.一些答案已针对Rust 1.0语法进行了更新.

Editor's note: This question was asked before Rust 1.0 and some of the syntax has changed since then, but the underlying concepts remain. Some answers have been updated for Rust 1.0 syntax.

我是Rust的新手,正在尝试对闭包做一些事情,这在JavaScript,Python等中是微不足道的.但是我遇到了Rust中的生命周期问题.我理解错误消息,但是它使我相信我想要做的事情在Rust中很难.

I'm new to Rust and trying to do something with closures which is trivial in JavaScript, Python, etc. but I am running into lifetime issues in Rust. I understand the error message, but it leads me to believe what I want to do is pretty hard in Rust.

我只想创建一个功能数组a,例如

I just want to create an array of functions, a, such that

  • a[0]是返回0的函数
  • a[1]是返回1的函数
  • ...
  • a[9]是返回9的函数
  • a[0] is the function returning 0
  • a[1] is the function returning 1
  • ...
  • a[9] is the function returning 9

我尝试过:

fn main() {
    let a : [||->uint,  ..10];
    for i in range(0u, 10) {
        a[i] = ||{i};
    }
    println!("{} {} {}", a[1](), a[5](), a[9]())
}

但是我遇到了终身错误.对于a中的函数,报告的错误是由于需求冲突而无法推断出适当的生存期",因为生存期无法超过while块,因此闭包也无法超过其堆栈框架,这当然是因为我在println!中调用它们.

But I got a lifetime error. The reported error was "cannot infer an appropriate lifetime due to conflicting requirements" for the functions in a because the lifetimes cannot outlive the while block so that the closures cannot outlive their stack frame, which of course they would because I am invoking them in println!.

我确定必须有一种构建这种功能数组的方法,但是如何?

I'm sure there must be a way to build up this array of functions, but how?

推荐答案

您需要使用move || i.

move表示此闭包将按值而不是引用采用i.默认情况下,这些闭包仅引用i.在您的情况下,这是被禁止的,因为i的生命周期仅限于循环的主体.

move implies that this closure will take i by value rather than by reference. By default, these closures would only take references to i. In your case it is forbidden as the lifetime of i is limited to the body of the loop.

此外,Rust会抱怨您的数组可能未完全初始化.为避免这种情况,您可以使用Vec<_>或使用std::mem::uninitialized:

Also, Rust will complain that your array may not be fully initialized. To avoid it, you can either use a Vec<_>, or use std::mem::uninitialized:

fn main() {
    let mut a: [_; 10] = unsafe { std::mem::uninitialized() };
    for i in 0..10 {
        a[i] = move || i;
    }
    println!("{} {} {}", a[1](), a[5](), a[9]())
}

这篇关于如何创建未装箱的函数/闭包数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆