My project dependencies:
// Cargo.toml
...
[dependencies]
md-5 = "0.10.6"
sha1 = "0.10.6"
I wish to create a function that takes a specified hash algorithm, and generates the corresponding digest.
The way to choose an algorithm is by hash enumeration.
// foo.rs
use md5::{Md5, Digest};
use sha1::Sha1;
pub enum Hash {
MD5,
SHA1
}
pub fn foo(content: &str, hash: Hash) -> String {
let mut hasher = match hash {
Hash::MD5 => Md5::new(),
Hash::SHA1 => Sha1::new(), // Error
};
hasher.update(content);
format!("{:x}", hasher.finalize_reset())
}
// main.rs
mod foo;
use foo::{foo, Hash};
fn main() {
let c = "Hello, World!";
let d = foo(c, Hash::MD5);
println!("{}", d);
}
When I try to run main.rs, the error occurred:
error[E0308]: `match` arms have incompatible types
--> src\foo.rs:13:23
|
11 | let mut hasher = match hash {
| ______________________-
12 | | Hash::MD5 => Md5::new(),
| | ---------- this is found to be of type `CoreWrapper<Md5Core>`
13 | | Hash::SHA1 => Sha1::new(),
| | ^^^^^^^^^^^ expected `CoreWrapper<Md5Core>`, found `CoreWrapper<Sha1Core>`
14 | | // Hash::SHA1 => Md5::new(),
15 | | };
| |_____- `match` arms have incompatible types
|
= note: expected struct `CoreWrapper<Md5Core>`
found struct `CoreWrapper<Sha1Core>`
For more information about this error, try `rustc --explain E0308`.
Clearly, I specified two different types of values for variable hasher, it caused an error.
But in Python, Everything is Object and Dynamic. I wish to call hasher succinctly like that, because CoreWrapper and CoreWrapper all have the same method.
I'd be better grateful if anyone is willing to give me an idea to achieve that.