Function std::convert::identity

pub const fn identity<T>(x: T) -> T

An identity function.

Two things are important to note about this function:

  • It is not always equivalent to a closure like |x| x since the closure may coerce x into a different type.

  • It moves the input x passed to the function.

While it might seem strange to have a function that just returns back the input, there are some interesting uses.


Using identity to do nothing among other interesting functions:

use std::convert::identity;

fn manipulation(x: u32) -> u32 {
    // Let's assume that this function does something interesting.
    x + 1

let _arr = &[identity, manipulation];

Using identity to get a function that changes nothing in a conditional:

use std::convert::identity;

let do_stuff = if condition { manipulation } else { identity };

// do more interesting stuff..

let _results = do_stuff(42);

Using identity to keep the Some variants of an iterator of Option<T>:

use std::convert::identity;

let iter = vec![Some(1), None, Some(3)].into_iter();
let filtered = iter.filter_map(identity).collect::<Vec<_>>();
assert_eq!(vec![1, 3], filtered);

© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.