std::ops::FnOnce

Trait std::ops::FnOnce

#[lang = "fn_once"]
pub trait FnOnce<Args> {
    type Output;
    extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
}

A version of the call operator that takes a by-value receiver.

Examples

By-value closures automatically implement this trait, which allows them to be invoked.

let x = 5;
let square_x = move || x * x;
assert_eq!(square_x(), 25);

By-value Closures can also be passed to higher-level functions through a FnOnce parameter.

fn consume_with_relish<F>(func: F)
    where F: FnOnce() -> String
{
    // `func` consumes its captured variables, so it cannot be run more
    // than once
    println!("Consumed: {}", func());

    println!("Delicious!");

    // Attempting to invoke `func()` again will throw a `use of moved
    // value` error for `func`
}

let x = String::from("x");
let consume_and_return_x = move || x;
consume_with_relish(consume_and_return_x);

// `consume_and_return_x` can no longer be invoked at this point

Associated Types

The returned type after the call operator is used.

Required Methods

???? This is a nightly-only experimental API. (fn_traits #29625)

This is called when the call operator is used.

Implementors

  • impl<'a, A, R> FnOnce<A> for Box<FnBox<A, Output = R> + 'a>
  • impl<'a, A, R> FnOnce<A> for Box<FnBox<A, Output = R> + 'a + Send>
  • impl<'a, A, F> FnOnce<A> for &'a F where
        F: Fn<A> + ?Sized
  • impl<'a, A, F> FnOnce<A> for &'a mut F where
        F: FnMut<A> + ?Sized
  • impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F>

© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/ops/trait.FnOnce.html

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部