Idiomatic alternative to reflection

I am trying to select a digest algorithm (from rust-crypto) based on the configuration line. In Python or JavaScript, let's say I would use reflection to understand:

getattr(Digest, myAlgorithm) 

... but from the fact that I was able to Google, this is not the best practice in a language such as Rust (plus I have not found any details on how to do this). My initial thought was to use pattern matching:

 let mut digest = match myAlgorithm { "sha256" => Sha256::new(), ... }; 

However, this does not work, because although all branches of the correspondence implement the same attribute, they are ultimately different types. Moreover, assuming that there is a way around this, it’s a lot of hassle to manually list all of these parameters in the code.

What is the right way to do this in Rust?

+6
source share
1 answer

Since all algorithms implement the same Digest attribute, which offers everything you need, you can insert all the algorithms and convert them into a general Box<Digest> :

 let mut digest: Box<Digest> = match my_algorithm { "sha256" => Box::new(Sha256::new()), ... }; 

Now you no longer know what a type is, but you still know its Digest .

Python and javascript do boxing (dynamic heap allocation) for you in the background. Rust is very picky about such things, and so you need to clearly indicate what you mean.

It would be interesting to have a reflection in Rust to be able to list all types in an area that implement a trait, but such a system would require quite a bit of effort in the rust compiler and in the brains of members of the rust community. Do not expect this soon.

+7
source

Source: https://habr.com/ru/post/988018/


All Articles