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
?
parse
returns acore::result::Result<u32, core::num::ParseIntError>
andunwrap
"moves the value v out of the Option if it is Some(v) [or] Panics if the self value equals None".parse
is a generic function, hence the type in angle brackets.You can use the
FromStr
trait'sfrom_str
method, which is implemented fori32
:With a recent nightly, you can do this:
What's happening here is that
String
can now be dereferenced into astr
. However, the function wants an&str
, so we have to borrow again. For reference, I believe this particular pattern (&*
) is called "cross-borrowing".You can directly convert to an int using the
str::parse::<T>()
method.You can either specify the type to parse to with the turbofish operator (
::<>
) as shown above or via explicit type annotation:As mentioned in the comments,
parse()
returns aResult
. This result will be anErr
if the string couldn't be parsed as the type specified (for example, the string"peter"
can't be parsed asi32
).Well, no. Why there should be? Just discard the string if you don't need it anymore.
&str
is more useful thanString
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 thanString
, and it is copyable, so it is not consumed by the invoked methods. In this regard it is more general: if you have aString
, you can pass it to where an&str
is expected, but if you have&str
, you can only pass it to functions expectingString
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.