Rust Deref Example

Here is an example showing the Deref usage:

struct Foo {
    pub val: String,
}

impl Deref for Foo {
    type Target = String;

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

fn ref_val(f: &Foo) {
    println!("{}", **f);
}

#[test]
pub fn test_deref() {
    let f = Foo { val: "foo".to_string() };
    println!("{}", *f);
    ref_val(&f);
}

Please note in above inside the ref_val(f: &Foo) function, it needs **f to deref the f object correctly.

Here is the code output:

My Github Page: https://github.com/liweinan

Powered by Jekyll and Theme by solid

If you have any question want to ask or find bugs regarding with my blog posts, please report it here:
https://github.com/liweinan/liweinan.github.io/issues