将字符串转换为整数? [英] Convert a String to int?

查看:65
本文介绍了将字符串转换为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这个问题包含不推荐使用的 1.0 之前的代码!不过答案是正确的.

要在 Rust 中将 str 转换为 int,我可以这样做:

To convert a str to an int in Rust, I can do this:

let my_int = from_str::<int>(my_str);

我知道如何将 String 转换为 int 的唯一方法是获取它的一部分,然后在其上使用 from_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());

有没有办法将String直接转换成int?

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

推荐答案

您可以使用 str::parse::() 方法.

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

您可以使用如上所示的 turbofish 运算符 (::<>) 或通过显式类型注释指定要解析的类型:

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

正如评论中提到的,parse() 返回一个 <代码>结果.如果无法将字符串解析为指定的类型(例如,字符串 "peter" 无法解析为 ,则此结果将是 Erri32).

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

这篇关于将字符串转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆