Is there a way to directly convert a String to an int ?
Is there a way to directly convert a String to an int ?
Yes, there is a way to directly convert a String to an int in Rust. The most common method to achieve this is by using the parse method provided by Rust's standard library. Here is a detailed explanation of how to do it:
parse MethodThe parse method is a generic function that can convert a string slice (&str) or a String into a specified type, such as an integer. The method returns a Result type, which can be either Ok(T) if the conversion is successful or Err(E) if it fails. Here is how you can use it:
fn main() {
let my_string = "42".to_string();
let my_int: i32 = my_string.parse().unwrap();
println!("{}", my_int); // Outputs: 42
}
In this example:
my_string is a String containing the value "42".parse::<i32>() method attempts to convert the string to a 32-bit signed integer.unwrap() method is used to handle the Result, panicking if the conversion fails.Instead of using unwrap(), which will panic on error, you can handle errors more gracefully using a match statement:
fn main() {
let my_string = "42a".to_string();
match my_string.parse::<i32>() {
Ok(n) => println!("Number: {}", n),
Err(e) => println!("Error: {}", e),
}
}
In this example, if the string cannot be parsed into an integer, the error is caught and printed instead of causing a panic.
When reading input from a user or another source, it is often useful to trim whitespace before parsing:
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
let trimmed = input.trim();
...
junior