功能锈阵列 [英] Rust array of functions

查看:196
本文介绍了功能锈阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的锈,并试图做闭包的东西是微不足道的JavaScript中,巨蟒等,但我遇到鲁斯特终身的问题。我理解的错误消息,但它使我相信我想要做的是pretty难生锈。

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

我试过( http://is.gd/mTycTC ):

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

但我得到了一生的错误。该报告的错误是不能推断适当的寿命因相互矛盾的要求为功能 A ,因为寿命不能经受住了,而块,使封锁不能活得比自己的堆栈帧,这当然他们​​会因为我调用它们在的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?

推荐答案

您需要使用移动|&放大器;:| {I} #![功能(unboxed_closures)]

基本上,移动意味着这个关闭将采取 I 通过值而不是引用。默认情况下,关闭经常只需要引用,在你的情况下,它是被禁止的的一生中,我仅限于身体循环。

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

您还需要添加&放大器; ,它指定闭合类型为的 FN (你需要&放大器; MUT: FnMut 的的 FnOnce )。目前,一个普通的 || 仍然是一个古老的关闭,但它最终应该的代名词|&放大器; MUT:|

You also need to add the &:, which specifies that the closure is of type Fn (you would need &mut: for FnMut and : for FnOnce). Currently a regular || is still an old closure, but it should eventually be a synonym of |&mut:|.

此外,铁锈会抱怨你的数组可能无法完全初始化。为了避免这个问题,你可以使用 VEC< _> ,或使用的std ::纪念品::初始化

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:

#![feature(unboxed_closures)]

fn main() {
    // The `_` tells rust to infer the type by itself.
    let mut a : [_,  ..10] = unsafe{std::mem::uninitialized()};
    for i in range(0u, 10) {
        a[i] = move |&:|{i};
    }
    println!("{} {} {}", a[1](), a[5](), a[9]())
}

这篇关于功能锈阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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