In this article, we will discuss how to convert a string to an integer in the Rust programming language.
Convert String to Int
To convert a string to an int in Rust, we can use the parse function to convert a string to an int in the Rust language. The parse function requires you to specify the type to convert to on the left side.
The syntax is as shown:
An example code is as shown below:
let string = "100";
let num: i32 = string.parse().unwrap();
println!("{}", num);
}
In the previous example, we convert a string to a 32-bit signed integer specified by a : i32.
We can also specify the type using the <> operator:
println!("{}", num);
Note: We use the unwrap() function to catch any errors that may arise from the conversion.
For example, trying to convert a non-digit string to an int would cause an error as shown below:
let string = "hello";
let num = string.parse::<i32>().unwrap();
println!("{}", num);
}
The previous code should return an error as you convert a non-digit string to int:
Convert String to Float
We can also convert a string to a float using the same parse function. Here, we can only specify the f64 as the type, as shown in the example below:
let float: f64 = string.parse().unwrap();
println!(“{}”, float)
}
The previous code should convert the string to a floating-point type.
Convert Char to Int
You can convert it to an int using the to_digit type if you have a character type. An example is as shown:
let num = ch.to_digit(10).unwrap();
println!("{}", num);
The previous example should convert the specified character to a string.
Conclusion
This article provided the guide to convert a string to an int, a string to a float, and a char to an int. We hope you found this article helpful. Check the other Linux Hint articles for more tips and information.