Convert from &str to i32

As the title states, how exactly do I convert from a &str to an i32? I see that i32 implements the from_str() function, but I'm not exactly sure how to use it. Any advice?

You want parse.

Example: Rust Playground

2 Likes

To directly answer your question though, this is how you'd use FromStr:

use std::str::FromStr;

fn main() {
    let n: u32 = FromStr::from_str("42").unwrap();
    println!("{}", n);
}

Thank you for your replies! Is there one solution to this problem that's "better" in any case? Or whichever I choose is fine?

parse seems to be the prevailing choice by thoughtful programmers. My guess is because:

  1. It's shorter.
  2. Doesn't require a use to bring a trait into scope.
  3. Can have type hints inlined, e.g., parse::<i32>(). FromStr::from_str can't do that, although I think type ascriptions might negate this benefit. (I can't remember if type ascriptions was rejected or if it just hasn't been implemented yet.)
2 Likes

Off the top of my head: <i32 as FromStr>::from_str("42") should do it.

2 Likes