Search code examples
rustacronymrust-result

What does "T" stand for in Result<T, E> in Rust?


The official documentation makes a lot of references to T:

enum Result<T, E> {
    Ok(T),
    Err(E),
}

I gather that these are placeholder acronyms. While E should stand for "error", I'm not sure what T stands for.


Solution

  • It's a naming convention for a generic type.

    Generic types in Rust are typically named with a single capital letter. The non_camel_case_types warning enforces that the name starts with a capital letter, but it's just a warning and nothing prevents you to name it otherwise.

    T is the most commonly seen letter, you'll often see this where the item really doesn't care what the type represents, but there are some other letters commonly used in particular cases as follow:

    • If the type is an error type: E. Example:

      fn err(self) -> Option<E>
      
    • If the type is a predicate: P. Example:

      fn filter<P>(self, predicate: P) -> Filter<Self, P>
      where
          P: FnMut(&Self::Item) -> bool, 
      
    • If the type is a function type: F, G, etc. Example:

      std::iter::Iterator::for_each<F>(self, f: F)
      where
          F: FnMut(Self::Item)
      
    • If the type is the return type of a generic function: R. Example:

      fn with<F, R>(&'static self, f: F) -> R
      where
          F: FnOnce(&T) -> R, 
      
    • If the type is a key type in some map: K. Example:

      fn keys(&self) -> Keys<K, V>
      
    • If the type is a value type in some map: V. Example:

      fn insert(&mut self, key: K, value: V) -> Option<V>
      
    • If the type is an implementation of Iterator: I. Example:

      impl<I> Clone for Fuse<I> where
          I: Clone, 
      
    • If the type is an implementation of Read: R. Example:

      fn chain<R: Read>(self, next: R) -> Chain<Self, R>
      where
          Self: Sized, 
      
    • If the type is an implementation of Write: W. Example:

      struct BufWriter<W: Write> { /* fields omitted */ }
      
    • If the type is an implementation of ToSocketAddrs: A. Example:

      fn connect<A: ToSocketAddrs>(addr: A) -> Result<TcpStream>
      
    • If the type is a path (ie. implements AsRef<Path>): P. Example:

      pub fn open<P: AsRef<Path>>(path: P) -> Result<File>
      
    • Everything else: T, U, etc., usually in alphabetical order.