470

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?

2

8 Answers 8

644

You can directly convert to an int using the str::parse::<T>() method, which returns a Result containing the int.

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();

Since parse() returns a Result, it will either 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), or an Ok with the value in it.

3
  • 2
    This is very helpful if you already know how to deal with Results. I suggest expanding the answer to accommodate anyone who doesn't. Mar 21, 2021 at 16:20
  • 19
    turbofish operator? Such a cool name. Never heard about that before :) Mar 25, 2022 at 21:35
  • @SaeedAhadian It's really the thing's name: doc.rust-lang.org/reference/… Nov 2 at 7:07
127
let my_u8: u8 = "42".parse().unwrap();
let my_u32: u32 = "42".parse().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.

0
55

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!");
3
  • 6
    Very important detail! Dec 5, 2021 at 6:23
  • Can you explain why ?
    – DataBach
    Sep 1 at 15:09
  • 1
    Ok found the answer in rust-book.cs.brown.edu. The trim method on a String instance will eliminate any whitespace at the beginning and end, which we must do to be able to compare the string to the i32, which can only contain numerical data. The user must press enter to satisfy read_line and input their guess, which adds a newline character to the string.
    – DataBach
    Sep 1 at 15:27
16

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".

2
  • Okay I am not on nightlies but I will accept it as an answer since I actually tried to dereference a String at one point and hoped it would work.
    – mmtauqir
    Nov 20, 2014 at 15:37
  • 2
    Alternatively, you can express my_sttring.as_slice() as my_string[] (currently slicing_syntax is feature-gated, but most probably some form of it would end up in the language). Nov 20, 2014 at 17:56
9

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);
0
8

Yes, you can use the parse method on a String to directly convert it to an integer lik so:

let my_string = "42".to_string();
let my_int = my_string.parse::<i32>().unwrap();

The parse method returns a Result object, so you will need to handle the case where the string cannot be parsed into an integer. You can use unwrap as shown above to get the value if the parse was successful, or it will panic if the parse failed.

Or you can use the match expression to handle the success and failure cases separately like so:

let my_string = "42".to_string();
let my_int = match my_string.parse::<i32>() {
    Ok(n) => n,
    Err(_) => {
        println!("Failed to parse integer");
        0
    },
};

FYI, the parse method is available for any type that implements the FromStr trait, which includes all of the integer types (e.g. i32, i64, etc.) as well as many other types such as f32 and bool.

2

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.

4
  • Well, an obvious reason for why "there should be", in my opinion, is that I wouldn't have to do .as_slice() every time I need to do from_str on a String. Command line arguments, for example, is one place where I need to do from_str on all the args to interpret them as ints etc.
    – mmtauqir
    Nov 20, 2014 at 15:35
  • as_slice() is only a minor aspect of string handling. For example, you can use slicing syntax (s[]) or exploit Deref coercion (&*s). There is even a proposal which would allow to write just &s. Nov 20, 2014 at 15:37
  • Ooooh! What would &s do for a string? Would it give a str back? Could you point me to the proposal?
    – mmtauqir
    Nov 20, 2014 at 15:38
  • 1
    First of all, str is not what you are working with; it is &str. They are different (but related). The former one is a dynamically sized type which you would almost never use directly, while the latter one is a string slice which is a fat pointer. The proposal is called deref coercions; it would allow to coerce from &T to &U if T: Deref<U>. Since String: Deref<str> already, you will be able to obtain &str from String with just &. It is still in discussion but I doubt it'll happen before 1.0 - there's too little time left. Nov 20, 2014 at 16:12
0

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.