271
votes

Note: this question contains deprecated pre-1.0 code! The answer is correct, though.

To convert a str to an int in Rust, I can do this:

let my_int = from_str::<int>(my_str);

The only way I know how to convert a String to an int is to get a slice of it and then use from_str on it like so:

let my_int = from_str::<int>(my_string.as_slice());

Is there a way to directly convert a String to an int?

7
See also: stackoverflow.com/q/32381414/500207 for non-decimal (i.e., hex).Ahmed Fasih
Somewhat obvious, but a note to anyone finding this question well after 2014, and wondering why from_str isn't in scope, it isn't in the prelude. use std::str::FromStr; fixes that. More on from_str if you'd like. doc.rust-lang.org/std/str/trait.FromStr.html#tymethod.from_strcryptograthor

7 Answers

377
votes

You can directly convert to an int using the str::parse::<T>() method.

let my_string = "27".to_string();  // `parse()` works with `&str` and `String`!
let my_int = my_string.parse::<i32>().unwrap();

You can either specify the type to parse to with the turbofish operator (::<>) as shown above or via explicit type annotation:

let my_int: i32 = my_string.parse().unwrap();

As mentioned in the comments, parse() returns a Result. This result will be an Err if the string couldn't be parsed as the type specified (for example, the string "peter" can't be parsed as i32).

76
votes
let my_u8: u8 = "42".parse::<u8>().unwrap();
let my_u32: u32 = "42".parse::<u32>().unwrap();

// or, to be safe, match the `Err`
match "foobar".parse::<i32>() {
  Ok(n) => do_something_with(n),
  Err(e) => weep_and_moan(),
}

str::parse::<u32> returns a Result<u32, core::num::ParseIntError> and Result::unwrap "Unwraps a result, yielding the content of an Ok [or] panics if the value is an Err, with a panic message provided by the Err's value."

str::parse is a generic function, hence the type in angle brackets.

22
votes

If you get your string from stdin().read_line, you have to trim it first.

let my_num: i32 = my_num.trim().parse()
   .expect("please give me correct string number!");
9
votes

With a recent nightly, you can do this:

let my_int = from_str::<int>(&*my_string);

What's happening here is that String can now be dereferenced into a str. However, the function wants an &str, so we have to borrow again. For reference, I believe this particular pattern (&*) is called "cross-borrowing".

5
votes

You can use the FromStr trait's from_str method, which is implemented for i32:

let my_num = i32::from_str("9").unwrap_or(0);
2
votes

Well, no. Why there should be? Just discard the string if you don't need it anymore.

&str is more useful than String when you need to only read a string, because it is only a view into the original piece of data, not its owner. You can pass it around more easily than String, and it is copyable, so it is not consumed by the invoked methods. In this regard it is more general: if you have a String, you can pass it to where an &str is expected, but if you have &str, you can only pass it to functions expecting String if you make a new allocation.

You can find more on the differences between these two and when to use them in the official strings guide.

0
votes

So basically you want to convert a String into an Integer right! here is what I mostly use and that is also mentioned in official documentation..

fn main() {

    let char = "23";
    let char : i32 = char.trim().parse().unwrap();
    println!("{}", char + 1);

}

This works for both String and &str Hope this will help too.