IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    Rust Deref coercion example

    金庆发表于 2021-08-22 04:31:00
    love 0
    # 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
        }
    }
    ```


    金庆 2021-08-22 12:31 发表评论


沪ICP备19023445号-2号
友情链接