zhimoe

Captain your own Ship.


  • 首页

  • 归档

  • 编程

  • 翻译

  • 随想

  • 关于

  • 搜索

Associated Type in Rust

2020-09-20   |   编程  

Associated Type and generic diff in rust

type outside impl

a type Foo = Bar outside is just type alias. most used in generic type.

like: type Thunk = Box<dyn Fn() + Send + 'static>;

type inside impl

type in an impl defines an associated type. associated type可以理解为一个类型占位符,在trait的方法声明中使用.

pub trait Iterator {
    type Item; // or type T: Display;

    fn next(&mut self) -> Option<Self::Item>;
}

这里Iterator的Implementors将会指定Item的具体类型.例如:

impl Iterator for Counter {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        // --snip--
    }
}

diff in associated type and generic

直接将上面的Iterator声明为如下泛型不是更简单么?

pub trait Iterator<T> { 
    fn next(&mut self) -> Option<T>;
}
//  with generice, you can set default type:
/// trait Iterator<T = String>
///    where T: Display,

主要的区别就是generic可是有任意多个实现,因为Iterator<Foo>和Iterator<Bar>是两个不同的类型.
而associated type只能有一个实现,因为Iterator只有一个类型,所以associated type可以用于限制类型.

when use

The quick and dirty answer to when to use generics and when to use associated types is:
Use generics if it makes sense to have multiple implementations of a trait for a specific type (such as the From<T> trait).
Otherwise, use associated types (like Iterator and Deref).

假设我们实现一个redis 客户端,那么比较适合使用associated types:

trait RedisCommand{
    type Response;
    fn receive(&self, message: String) -> Result<Self::Response>;
}

impl RedisCommand for PingCommand {
    type Response = String
    
    fn receive(&self, message: String) -> Result<Self::Response>{
        // -- snip --
    }
}
#rust
Buy me a coffee
如何实现一个拼写检查器[翻译]
最佳编程字体
评论加载中... 如果长时间无法加载,请针对 giscus.app 启用代理。
  • 文章目录
  • 站点概览
zhimoe

zhimoe

72 日志
4 分类
45 标签
GitHub ZhiHu
书签
  • 可视化Git
  • 绘画博物馆
  • Rust小抄
  • 谷歌机器学习
标签云
  • code
  • java
  • python
  • scala
  • rust
  • spring
  • qq空间
  • 并发
  • git
  • docker
  • aop
  • async
  • type outside impl
  • type inside impl
  • diff in associated type and generic
  • when use
2016 - 2023 zhimoe
0%