{

How to Convert String to Int and int to String in Rust example


This tutorial explains about following things

  • How to parse a string to int in Rust?
  • How to convert an int into a String
  • How to read the input from the console and convert it to Integer?

For example, if the string is “123”, It converts to an integer type 123 value.

There are multiple ways we can do the conversion.

How to convert a String to int in Rust?

This example converts a string to int with an example using the parse() method. String parse() method return Result object. call unwrap method to return integer type

Here is an example program

fn main() {

    let str = "123";
    let number: u32 = str.parse().unwrap();

    println!("{}", number);
}

Output:

123

In the below example, if string contains non numeric digits, parse() method throws ParseIntError.

Here is an example program

fn main() {
    let str = "123abc";
    let number: u32 = str.parse().unwrap();

    println!("{}", number);
}

It throws ParseIntError on running above program

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 seen a program to read the string from the console, and convert it into integer type in rust.

  • print the string to console
  • Create a mutable new string
  • read the console input as String using read_line() function,
  • trim the string and call the parse() method which returns the 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 int to String in Rust?

This example converts an int to a string with an example using the to_string() method. String to_string() method returns string version of integer type

Here is an example program

fn main() {
    let number: u8 = 11;
    let str: String = number.to_string();
    println!("{}", str);
}

Output:

11

Conclusion

To summarize, Learn multiple ways to convert string to/from integer types in rust with examples

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.