rust - How to conditionally assign a type to a reference -
i have been playing rust afternoon , decided write simple hashing tool can major digesting algorithms.
i'm trying (intent should obvious):
let mut hasher; match alg { "md5" => { hasher = md5::new() } "sha1" => { hasher = sha1::new() } _ => { println!("algorithm not implemented"); process::exit(1); } } hash_file(&file_name, &mut hasher).unwrap(); when compiling above, due first match, assumes hasher of type md5 , fails when in "sha1" match branch, tries assign sha1 type. of types intend use in match statement implementers of trait digest feel there should way this.
i tried:
let mut hasher: digest; but didn't work either.
it sounds want use trait objects. example this:
let mut hasher; match alg { "md5" => { hasher = box::new(md5::new()) box<digest>} "sha1" => { hasher = box::new(sha1::new()) box<digest>} _ => { println!("algorithm not implemented"); process::exit(1); } } hash_file(&file_name, &mut hasher).unwrap(); this work under conditions (for example, trait has object safe), think it's way want.
Comments
Post a Comment