Rust匿名类型

简明扼要闭包从封闭范围内捕捉变量。这是否有什么后果? 它肯定不会。观察一下在函数中调用一个封闭泛型要求,这是因为它们定义如何要求:

// `F` must be generic.
fn apply<F>(f: F) where
    F: FnOnce() {
    f()
}

当封闭件被定义,编译器隐式地创建一个新的匿名结构到内部存储所捕获的变量,通过之一 traitsFnFnMut, 或 FnOnce 这种未知类型来实现功能 这种类型被分配给被存储直到调用变量。

由于这种新型的未知类型的,在功能的任何使用都需要泛型。但是,无限制类型参数(<T>)仍然是不明确的,不会被允许。 因此,边界是由所述一个 traitsFnFnMut, 或FnOnce (实现)足以指定它的类型。

// `F` must implement `Fn` for a closure which takes no
// inputs and returns nothing. Exactly what is required
// for `print`.
fn apply(f: F) where
    F: Fn() {

    f()
}

fn main() {
    let x = 7;

    // Capture `x` into an anonymous type and implement
    // `Fn` for it. Store it in `print`.
    let print = || println!("{}", x);

    apply(print);
}

联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2022

备案号:京ICP备15003423号-3