Wednesday, December 9, 2020

How to make dereference for your struct in Rust

 Dereference operator ( *)  in Rust


Dereference operator we have seen in C programming language. Yes , I am talking about the ' * ' operator that we use for dereferencing a pointer in C.

I am not sure how * operator works behind the seen, but the it dereference the pointer and give us the value in that address. 

But in Rust implementation is more obvious  that the type has to implement the trait 'Deref".

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


So let's see how should be convert our struct to dereference the value whatever way that we like.


Rust  Deref example

This is simple program to use * operator on MyStruct. And it is only to demonstrate the capabilities of Deref trait, not an idiomatic code.

Here we are derefencing the second field value when we use * operator on MyStruct instance.

use std::ops::Deref; struct MyStruct{ x: i32, y:String, } impl Deref for MyStruct{ //the Deref trait implementation should have Target //associated type type Target = String; // trait mandotory function implementation fn deref(&self) -> &Self::Target{ &self.y } } fn main(){ let my = MyStruct { x:4,y:"hello".to_string() }; //derefencing our struct with * operator println!("{}",*my); }



Conclusion:

Even though references and dereferencing are essential part of most of the system programming languages, how they are implemented  are always hidden behind the language implementations ( in my knowledge) . But Rust gives that insight and flexibility to use them on custom references.



No comments: