Convert a String to int in Rust?

2019-01-03 18:10发布

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?

标签: rust
5条回答
We Are One
2楼-- · 2019-01-03 18:34
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(),
}

parse returns a core::result::Result<u32, core::num::ParseIntError> and unwrap "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.

查看更多
走好不送
3楼-- · 2019-01-03 18:37

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);
查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-03 18:40

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".

查看更多
叼着烟拽天下
5楼-- · 2019-01-03 18:42

You can directly convert to an int using the str::parse::<T>() method.

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

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

查看更多
淡お忘
6楼-- · 2019-01-03 18:46

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.

查看更多
登录 后发表回答