W3cubDocs

/Rust

Trait std::ops::Fn

pub trait Fn<Args>: FnMut<Args> {
    extern "rust-call" fn call(&self, args: Args) -> Self::Output;
}

A version of the call operator that takes an immutable receiver.

Examples

Closures automatically implement this trait, which allows them to be invoked. Note, however, that Fn takes an immutable reference to any captured variables. To take a mutable capture, implement FnMut, and to consume the capture, implement FnOnce.

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

Closures can also be passed to higher-level functions through a Fn parameter (or a FnMut or FnOnce parameter, which are supertraits of Fn).

fn call_with_one<F>(func: F) -> usize
    where F: Fn(usize) -> usize {
    func(1)
}

let double = |x| x * 2;
assert_eq!(call_with_one(double), 2);

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, F> Fn<A> for &'a F where F: Fn<A> + ?Sized

© 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.Fn.html