We have answer of your question!

100% solved queries, no empty question

Question: Generic function to parse numbers fails with "FromStr is not implemented"


0

Advertisement


I have this generic function in my Rust code:

fn test<T>(text: &str) -> T {
    text.parse::<T>()
}

The idea is that the caller would do something like

test::<u64>("2313");

But the compilation fails with this message

error: the trait `core::str::FromStr` is not implemented for the type `T` [E0277]

I just started learning Rust yesterday, so this is probably a very basic question that I've failed to find the answer to.

Question author Sassa | Source

Answer


1


Advertisement


Like the error message states, T needs to implement core::str::FromStr in order to be applicable for the parse function. The type signature of parse is:

fn parse<F>(&self) -> Result<F, F::Err> where F: FromStr

Which limits the sort of F (or, in your case T) you can use to those implementing FromStr. Your other problem is the type returned by test; it should be the same as the one of parse - a Result.

When you fix those issues, your function will work:

use std::str::FromStr;

fn test<T: FromStr>(text: &str) -> Result<T, T::Err> {
    text.parse::<T>()
}

fn main() {
    println!("{:?}", test::<u64>("2313"));
}

Ok(2313)

Answer author Ljedrz

Advertisement


Tickanswer.com is providing the only single recommended solution of the question Generic function to parse numbers fails with "FromStr is not implemented" under the categories i.e generics , rust , . Our team of experts filter the best solution for you.

Related Search Queries:

You may also add your answer!