-1

I am trying to understand the source code of the array::map function. The docs show this as the signature

pub fn map<F, U>(self, f: F) -> [U; N]
where
    F: FnMut(T) -> U, 

i know F represents function, the N is kind of like a fixed length. What does the U stand for? It takes a function/closure that returns a U ? does it mean unsigned array?

user1003967
  • 137
  • 2
  • 11
  • https://learning-rust.github.io/docs/b4.generics.html – Denys Séguret Dec 09 '21 at 19:35
  • 4
    See also [“What does `T` stand for in `Result` in Rust?”](https://stackoverflow.com/questions/60590029/what-does-t-stand-for-in-resultt-e-in-rust/60590428) – mcarton Dec 09 '21 at 19:42
  • `U` is the return value of the function passed to `array::map`. `array::map` converts array of `T` to array of `U` by applying the given function to every element of the array, and creating a new array out of results. If you have an array of gadgets, you can use `.map()` to convert it to an array of widgets simply by calling `map()` with a function that takes a gadget and returns a widget. – user4815162342 Dec 09 '21 at 19:51
  • 1
    As for why it was chosen - I guess that `T` usually stands for arbitrary `T`ype, and `U` is just the next letter in the alphabet, so it is used as the _second_ type. – Cerberus Dec 10 '21 at 02:00

1 Answers1

1

U can be any type. U is an unrestricted generic type parameter.

If you write a function foo like this and pass it to map (map(foo)) then rust will figure out that U is bool here. Because the parameter F is of the type fn(u64) -> bool (I assumed here that T is u64 as an example)

fn foo(_arg: u64) -> bool {
  ...
}

If you wrote a function bar like this and pass it to map (map(bar)) then rust will figure out that U is String here. Because the parameter F is of the type fn(u64) -> String

fn bar(_arg: u64) -> String {
  ...
}
user4815162342
  • 141,790
  • 18
  • 296
  • 355
Jeroen Vervaeke
  • 1,040
  • 9
  • 20