Rust Deref coercion example

Posted 金庆

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Rust Deref coercion example相关的知识,希望对你有一定的参考价值。

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
    }
}

以上是关于Rust Deref coercion example的主要内容,如果未能解决你的问题,请参考以下文章