金庆的专栏

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  423 随笔 :: 0 文章 :: 454 评论 :: 0 Trackbacks
# Rust Deref coercion example

https://doc.rust-lang.org/std/ops/trait.Deref.html

```
use std::ops::Deref;

struct DerefExample<T> {
    value: T
}

impl<T> Deref for DerefExample<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

let x = DerefExample { value: 'a' };
assert_eq!('a', *x);
```

Deref coercion can be used in newtype:
```
struct MyI32(i32)

impl Deref for MyI32 {
    type Target = i32;
    
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
```
posted on 2021-08-22 12:31 金庆 阅读(171) 评论(0)  编辑 收藏 引用 所属分类: 9. 其它

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理