HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

Convert a String to int?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
stringconvertint

Problem

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::(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::(my_string.as_slice());


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

Solution

You can directly convert to an int using the str::parse::() 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::().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.

Code Snippets

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

Context

Stack Overflow Q#27043268, score: 743

Revisions (0)

No revisions yet.