可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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::(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::(my_string.as_slice());
Is there a way to directly convert a String to an int?
回答1:
You can directly convert to an int using the str::parse::() method.
let my_string = "27".to_string(); // `parse()` works with `&str` and `String`! let my_int = my_string.parse::().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).
回答2:
let my_u8: u8 = "42".parse::().unwrap(); let my_u32: u32 = "42".parse::().unwrap(); // or, to be safe, match the `Err` match "foobar".parse::() { Ok(n) => do_something_with(n), Err(e) => weep_and_moan(), }
parse returns a core::result::Result 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:
With a recent nightly, you can do this:
let my_int = from_str::(&*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".
回答4:
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.