I have a function which is supposed to check command line arguments and according to what the input is mutate the image. I know how to mutate the image outside of the scope of the for loop but it doesn't return the mutated image object.
I'm having trouble mutating the object and returning it, and I'm too inexperienced to understand how I should overcome this issue.
fn commands(args: Vec<String>, img1: &DynamicImage) -> DynamicImage {
let length = args.len();
let img2 = img1.clone();
for n in 2..length{
if &args[n] == "90"{
img2.rotate90();
return img2
}else if &args[n] == "180"{
img2.rotate180();
return img2
}else if &args[n] == "270"{
img2.rotate270();
return img2
}else{
eprintln!("Invalid input")
}
return img2
}
return img2
}
CodePudding user response:
You return the original, not the rotated image. One way I can tell at a glance is that img2
is not mutable so it is unlikely you are modifying the current image. Upon checking the documentation, it does indeed return a new image.
Here is one way you could rewrite it that would do this:
fn commands(args: Vec<String>, img: &DynamicImage) -> DynamicImage {
for arg in &args[2..] {
match arg.as_ref() {
"90" => return img.rotate90(),
"180" => return img.rotate180(),
"270" => return img.rotate270(),
_ => eprintln!("Invalid input"),
}
}
img.clone()
}
You may want to consider returning an Option<DynamicImage>
or Result<DynamicImage, InvalidDegreesError>
(where InvalidDegreesError
is some custom error type) instead to improve the functionality. Also, if the args
field represents command line arguments, then you may want to consider using a crate like clap
to handle input verification.