451

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?

vallentin
  • 23,478
  • 6
  • 59
  • 81
mmtauqir
  • 8,499
  • 9
  • 34
  • 42
  • 1
    See also: http://stackoverflow.com/q/32381414/500207 for non-decimal (i.e., hex). – Ahmed Fasih Dec 16 '16 at 01:08
  • 5
    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. https://doc.rust-lang.org/std/str/trait.FromStr.html#tymethod.from_str – cryptograthor Mar 02 '20 at 15:18

8 Answers8

625

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.

TankorSmash
  • 12,186
  • 6
  • 68
  • 106
John Vrbanac
  • 6,374
  • 1
  • 14
  • 3
122
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.

Jared Beck
  • 16,796
  • 9
  • 72
  • 97
53

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!");
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Ade Yahya
  • 717
  • 5
  • 6
  • 6
    Very important detail! – Marco Antonio Dec 05 '21 at 06:23
  • Can you explain why ? – DataBach Sep 01 '23 at 15:09
  • 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 01 '23 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".

DK.
  • 55,277
  • 5
  • 189
  • 162
  • 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 '14 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). – tempestadept Nov 20 '14 at 17:56
8

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);
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Karthik Cherukuri
  • 603
  • 2
  • 9
  • 15
5

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.

AlexaP
  • 179
  • 2
  • 1
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.

Vladimir Matveev
  • 120,085
  • 34
  • 287
  • 296
  • 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 `int`s etc. – mmtauqir Nov 20 '14 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`. – Vladimir Matveev Nov 20 '14 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 '14 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](https://github.com/rust-lang/rfcs/pull/241); it would allow to coerce from `&T` to `&U` if `T: Deref`. Since `String: Deref` 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. – Vladimir Matveev Nov 20 '14 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.

D. Lawrence
  • 943
  • 1
  • 10
  • 23
Taimoor
  • 67
  • 8