Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic alternative to reflection

I am trying to select a digest algorithm (from rust-crypto) based on a configuration string. In Python or JavaScript, say, I'd probably use reflection to get at this:

getattr(Digest, myAlgorithm)

...but from what I've been able to Google, this isn't best practice in a language such as Rust (plus I've found no details on how it could be done). My initial thought was to use a pattern match:

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

However, this doesn't work because, while all the branches of the match implement the same trait, they're ultimately different types. Moreover, presuming there were a way around this, it's a lot of hassle to manually enumerate all these options in the code.

What's the right way to do this in Rust?

like image 228
Xophmeister Avatar asked May 27 '15 15:05

Xophmeister


1 Answers

Since all the algorithms implement the same trait Digest, which offers everything you need, you can box all the algorithms and convert them to a common Box<Digest>:

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

Now you don't know anymore what the type was, but you still know it's a Digest.

The python and javascript do the boxing (dynamic heap allocation) for you in the background. Rust is very picky about such things and therefor requires you to explicitly state what you mean.

It would be interesting to have reflection in Rust to be able to enumerate all types in scope that implement a trait, but such a system would require quite some effort in the rust compiler and in the brains of of the rust community members. Don't expect it any time soon.

like image 109
oli_obk Avatar answered Sep 19 '22 21:09

oli_obk