rust - Rust 中的 Result<T, E> 中的 "T"代表什么?

标签 rust acronym rust-result

官方documentation大量引用 T:

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

我认为这些是占位符首字母缩略词。虽然 E 应该代表“错误”,但我不确定 T 代表什么。

最佳答案

这是通用t类型的命名约定。

Rust 中的泛型类型通常以单个大写字母命名。 non_camel_case_types警告强制名称以大写字母开头,但这只是一个警告,没有什么可以阻止您以其他方式命名。

T是最常见的字母,你会经常看到这个项目实际上并不关心类型代表什么,但是在特定情况下还有一些其他常用字母如下:

  • 如果类型是错误类型:E . Example:

    fn err(self) -> Option<E>
    
  • 如果类型是谓词:P . Example:

    fn filter<P>(self, predicate: P) -> Filter<Self, P>
    where
        P: FnMut(&Self::Item) -> bool, 
    
  • 如果类型是函数类型:F , GExample:

    std::iter::Iterator::for_each<F>(self, f: F)
    where
        F: FnMut(Self::Item)
    
  • 如果类型是泛型函数的返回类型:R . Example:

    fn with<F, R>(&'static self, f: F) -> R
    where
        F: FnOnce(&T) -> R, 
    
  • 如果类型是某个映射中的键类型:K . Example:

    fn keys(&self) -> Keys<K, V>
    
  • 如果类型是某个映射中的值类型:V . Example:

    fn insert(&mut self, key: K, value: V) -> Option<V>
    
  • 如果类型是 Iterator 的实现: I . Example:

    impl<I> Clone for Fuse<I> where
        I: Clone, 
    
  • 如果类型是 Read 的实现: R . Example:

    fn chain<R: Read>(self, next: R) -> Chain<Self, R>
    where
        Self: Sized, 
    
  • 如果类型是 Write 的实现: W . Example:

    struct BufWriter<W: Write> { /* fields omitted */ }
    
  • 如果类型是 ToSocketAddrs 的实现: A . Example:

    fn connect<A: ToSocketAddrs>(addr: A) -> Result<TcpStream>
    
  • 如果类型是路径(即实现 AsRef < Path > ):P . Example:

    pub fn open<P: AsRef<Path>>(path: P) -> Result<File>
    
  • 其他一切:T , U等,通常按字母顺序排列。

关于rust - Rust 中的 Result<T, E> 中的 "T"代表什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60590029/

相关文章:

Rust 从 fn : mismatched types 返回结果错误

rust - 避免在结果链中多次调用 `map_err`

python - 带有句号的首字母缩略词 python

java - DTO、DAO 和 DCO。什么是 DCO?

struct - 为什么要在结构中对引用使用相同的生命周期?

rust - 如何实现动态列表 "middleware"函数?

css - 字段集图例中的 IE7 首字母缩略词下划线

generics - 确定类型时 match 和 unwrap_or 的区别

linux - 在 i::count 上运行收集时得到 "Illegal instruction"

rust - 借用的值没有足够长的时间,试图公开迭代器而不是数据的具体 Vec 表示