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
?
This question is related to
rust
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);
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.
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.
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!");
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".
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.
Source: Stackoverflow.com