530

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

738

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.

Sign up to request clarification or add additional context in comments.

5 Comments

This is very helpful if you already know how to deal with Results. I suggest expanding the answer to accommodate anyone who doesn't.
turbofish operator? Such a cool name. Never heard about that before :)
@SaeedAhadian It's really the thing's name: doc.rust-lang.org/reference/…
Because it really looks like a fish or a submarine or both: <i32>()
Check out turbo.fish
135
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.

1 Comment

easier to use if let Ok(n) = "foobar".parse::<i32>() { } else { }
62

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!");

2 Comments

Can you explain why ?
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.
15

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 Comments

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.
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).
10

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

Comments

5

Adding on to other answers, using unwrap_or is another option for quick error handling

let my_string = "42";
let my_int = my_string.parse::<i32>().unwrap_or(0);

4 Comments

"Safer" depends on the use-case. Do you want to have a fallback value of zero? If yes, this is not just safer, this is just the correct code and anything else is incorrect. Do you not want it? I'd argue unwrap() is safer (offensive programming), or use proper error handling. Falling back to zero will just result in weird bugs later. Also, this is really not the place for this answer, it can maybe be at stackoverflow.com/q/63859927/7884305 or at stackoverflow.com/q/64996954/7884305. Here it should be at most a comment.
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
Okay, I'll change that. The link for the documentation : unwrap
Instead of calling it safer, I'll label it as just another option.
3

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 Comments

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.
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.
Ooooh! What would &s do for a string? Would it give a str back? Could you point me to the proposal?
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.
1

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.