Type annotations needed solution?

I can't figure out why this error is occurring as I have annotated the error both in the definition and usage. As a result I can't find a solution. Help? Mostly I'd like to know why it's required. It doesn't feel like it should be.

function definition:
async fn token_check() -> Result<TokenResponse, (std::io::ErrorKind,String)>
returned item:
Err((std::io::ErrorKind::Other, "invalid request type"))

error:
"type annotations needed cannot infer type of the type parameter `T` declared on the enum `Result`"

compiler recommendation:
Err::<T, (std::io::ErrorKind, &str)>((std::io::ErrorKind::Other, "invalid request type"))

error after compiler recommended correction:
cannot find type `T` in this scope not found in this scope

Please post the actual code that triggers this error.

That's going to be challenging. It's over 100 lines including a few database calls. Let me see if I can clean it up and post in a few minutes.

T is the type of the Ok value of the Result<T, E> type. This generic type cannot be inferred by the compiler in this case, requiring to writing something like

Err::<T, _>((std::io::ErrorKind::Other, "invalid request type"))

replacing T with the actual type. If it does not matter or the function doesn't return anything on success, you can use the unit type () as follows:

Err::<(), _>((std::io::ErrorKind::Other, "invalid request type"))

It is returning an Ok type that is listed in the function definition listed. The Error type returned is a Tuple of an ErrorKind and a String. This is because you can't clone an Error and I currently have a need to clone an Error elsewhere.

Anyway, the types are in in the function definition and it's complaining about an error returned.

That said, I found my incorrect code while researching your response in my code.
I added the return keyword and I was not returning the correct tuple. I defined the function with a String and I was returning an &str. So adding .to_string() and the return keyword.
Problem is resolved. Thank you both!

Corrected Line: return Err((std::io::ErrorKind::Other, "invalid request type".to_string()))

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.