How to Convert String to Int and int to String in Rust example
This tutorial covers the following topics:
- How to parse a string to an integer in Rust?
- How to convert an integer into a string?
- How to read input from the console and convert it to an integer?
For example, if the string is 123
, It converts to an integer type 123 value.
There are various methods to perform these conversions.
How to Convert a String to an Integer in Rust?
This example demonstrates how to convert a string to an integer using the parse()
method. The parse()
method returns a Result object. You can use the unwrap
method to obtain the integer value.
Here is an example program
fn main() {
let str = "123";
let number: u32 = str.parse().unwrap();
println!("{}", number);
}
Output:
123
In the following example, if the string contains non-numeric characters, the parse()
method throws a ParseIntError
.
Here’s the program:
fn main() {
let str = "123abc";
let number: u32 = str.parse().unwrap();
println!("{}", number);
}
Running the above program throws a ParseIntError
.
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', test.rs:7:35
note: run with the `RUST_BACKTRACE=1` environment variable to display a backtrace
Let’s see a program to read a string from the console and convert it into an integer type in Rust.
- Print the prompt to the console.
- Create a mutable string.
- Read the console input as a string using the
read_line()
function. - Trim the string and call the
parse()
method, which returns a Result object. - Convert the result to type
u32
.
use std::io;
fn main() {
println!("Please enter Age?");
let mut line = String::new();
io::stdin().read_line(&mut line).expect("Error to read");
let age: u32 = line.trim().parse().expect("Expect a number");
println!("{}", age);
}
Please enter Age?
123
123
How to Convert an Integer to a String in Rust?
This example demonstrates how to convert an integer to a string using the to_string()
method. The to_string()
method returns the string version of the integer.
Here is an example program
fn main() {
let number: u8 = 11;
let str: String = number.to_string();
println!("{}", str);
}
Output:
11
Conclusion
In summary, learn multiple ways to convert strings to and from integer types in Rust with examples.