问题:
Convert a String to int in Rust?
在Rust中一个字符串如何转化为整型?
Note: this question contains deprecated pre-1.0 code! The answer is correct, though.
注意,这个问题包含已经废弃的pre-1.0的代码。不过,这个答案是正确的。
To convert a str to an int in Rust, I can do this:
rust中一个str转化为一个int,我能够做这些:
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:
一个String转化为int,我知道的唯一的方式是获得它的slice,然后使用 from_str方法,像这样:
let my_int = from_str::<int>(my_string.as_slice());
Is there a way to directly convert a String to an int?
有方法可以直接将一个String转化为一个int么?
See also: stackoverflow.com/q/32381414/500207 for non-decimal (i.e., hex).
也可以看:stackoverflow.com/q/32381414/500207 ,对于非十进制(比如16进制)
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. doc.rust-lang.org/std/str/trait.FromStr.html#tymethod.from_str
比较明显的,但是有一个提醒,对于在2014年后找到这个问题的人,并且想知道为什么from_str不在范围内,因为它没有预加载。use std::str::FromStr;使用这个修复它。如果你想知道更多关于from_str,doc.rust-lang.org/std/str/trait.FromStr.html#tymethod.from_str。
回答:
You can directly convert to an int using the str::parse::<T>() method.
你可以直接使用str::parse::<T>()方法转化为一个整型。
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:
你可以使用turbofish操作符(::<>),如上面所示,指定解析类型,也可以通过显示的类型注解:
let my_int: i32 = my_string.parse().unwrap();
As mentioned in the comments, parse() returns a Result. This result will 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).
正如评论中提到的, parse()返回一个Result。如果字符串不能被解析为指定类型,这个结果会是一个Err。(举个例子,字符串"peter"不能被解析为i32类型)
Note that parse returns a Result, so you need to deal with that appropriately to get to an actual integral type.
注意parse返回一个Result,所以为了得到一个实际的数字类型,你需要适当的处理它。