我认为以下代码不言自明。
extern crate crypto;
use crypto::sha2::Sha256;
use crypto::md5::Md5;
use crypto::digest::Digest;
fn main() {
let mut args = std::env::args();
let _ = args.next().expect("unknown argument environment...");
let command = args.next().expect("no command given...");
let data = args.next().expect("no data given...");
let mut digest: Digest = match command.as_ref() {
"md5" => Md5::new(),
"sha256" => Sha256::new(),
_ => panic!("algorithm not supported")
};
digest.input_str(&data);
print!("{} of \"{}\" is \"{}\"", command, data, digest.result_str());
}
据我所知,traits用于告诉编译器一组特定的方法可用于特定类型。在这种情况下,input_str
和result_str
方法可用于Sha256
和Md5
,因为它们正在实施特征Digest
。但是,我无法弄清楚如何告诉Rust我想继续使用Digest
特征的方法。
编译器输出为:
src/main.rs:15:21: 15:31 error: mismatched types:
expected `crypto::digest::Digest`,
found `crypto::md5::Md5`
(expected trait crypto::digest::Digest,
found struct `crypto::md5::Md5`) [E0308]
src/main.rs:15 "md5" => Md5::new(),
^~~~~~~~~~