Beginner question on how to use api documentation

I need to better understand how to read rust api documentation.

For example, I went to write this line of code :

let orderID: Result<i64, > = orderid_param.parse();

Didn't know what to put in the Error portion. I went to the docs for parse

The only thing that makes sense to me is


Will return Err if it’s not possible to parse this string slice into the desired type.

So, I typed out this :

let orderID_: Result<i64,Err("ok")> = orderID.parse();

But this didn't work either. Got syntax errors.
I'm sure, I could find concrete examples out there, but would like to know how to go about it via the docs.

First of all, Err(…) is a value, not a type. Since Err is a variant ("constructor" if you like) of enum Result, if you invoke it, you get a value of type Result. You won't get a value of the error type itself, much less a type.

The method signature reads:

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

which means that the error type is whatever associated type is specified by the type F in its impl FromStr implementation. In your case, F is i64, so you can go to its documentation and look for its FromStr implementation, which reads, among others:

type Err = ParseIntError;

So that's what the error type is.

(Here, Err is a type variable for an associated type of the FromStr trait; it has nothing to do with the Err variant of Result. It's not meaningful in itself, only in the context of the FromStr trait and any concrete types implementing that trait.)

Anyway, in this specific case, you can just put _ instead, and let the compiler infer the error type, since it's unambiguous:

let orderID: Result<i64, _> = orderid_param.parse();

thank you! thank you

A great trick here: just put something wrong, and the compiler will often tell you what to put.

For example, if you write

let orderID: Result<i64, ()> = orderid_param.parse();

Then the compiler error says

error[E0271]: type mismatch resolving `<i64 as FromStr>::Err == ()`
 --> src/
3 |     let orderID: Result<i64, ()> = orderid_param.parse();
  |                                                  ^^^^^ expected struct `ParseIntError`, found `()`

So you can take that to get

let orderID: Result<i64, ParseIntError> = orderid_param.parse();

Which still won't quite work, but the compiler will help again:

help: consider importing one of these items
1 | use std::num::ParseIntError;
1 | ...

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.