let image: DynamicImage = match image::load_from_memory(&img_bytes) {
Ok(img) => img,
Err(error) => panic!("Problem loading the image from memory: {:?}", error),
};
This is my code above and it works. However when I try to explicitly add the type in the Ok() as this. It throws a syntax error.
let image: DynamicImage = match image::load_from_memory(&img_bytes) {
Ok(img: DynamicImage) => img,
Err(error: ImageError) => panic!("Problem loading the image from memory: {:?}", error),
};
This is the error
error: expected one of `)`, `,`, `@`, or `|`, found `:`
--> src\main.rs:65:15
|
65 | Ok(img: DynamicImage) => img,
| ^ expected one of `)`, `,`, `@`, or `|`
I thought the type was just wrong however when I enable inlay hints in vscode it gives the exact same type. This happens in any match statement. I’m new to rust and I’m confused why this is happening. Any help is appreciated.
Here’s a link to a playground example of the problem I’m having https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=d08177237e4c58ce379f034a3107d93b
If you remove the : file and : Error it works as expected. But isn’t that the types? Why do I need to remove them?
>Solution :
use std::fs::File;
use std::io::Error;
fn main() {
match File::open("Example.txt") {
Ok::<File, _>(file) => file,
Err::<_, Error>(error) => panic!("Could not open file: {:?}", error),
};
}
The explicit type is in the Ok and Result, which has two generics so you need to use turbofish to accomplish that.
I also added _ since the compiler knows exactly the type is for when I don’t need the explicit type, Error for the Ok, for example. You could, obviously, add the explicit type to both generics if you want.
Here is your example on playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6aa586996596d46549dbcf59a89157bc