How to convert string to int in Rust

In this example, we are going to learn about How to convert string to int in Rust. We will learn this with multiple code examples.

so let us begin with our program examples.

1. Convert string to int Using trim(),parse(), wrap() function


In our first approach we are going to make use of trim(), parse(), and unwrap() functions of strings.
This approach works for both String and &str strings in Rust.

fn main() {

    let char = "43";
    let num : i32 = char.trim().parse().unwrap();
    println!("The converted number is :");
    println!("{}", num + 1);

}

Output

rustc -o main main.rs
./main
The converted number is :
44

2. Convert string to int in Rust using from_str() function


In this example, we are going to use another approach. This approach makes use of the from_str() function of the FromStr trait.

Let us first understand this in detail before we jump to the code example.

Rust from_str() methods

from_str() methods Parse a value from a string. FromStr’s from_str() method is often used implicitly, through str’s parse method. This we saw in the example above. FromStr does not have a lifetime parameter, and so you can only parse types that do not contain a lifetime parameter themselves. In other words, you can parse an i32 with FromStr, but not a &i32.You can parse a struct that contains an i32, but not one that contains an &i32.

Syntax:

pub trait FromStr {
    type Err;
    fn from_str(s: &str) -> Result<Self, Self::Err>;
}

Rust Program to convert string to int

use std::str::FromStr;

fn main() {

		let s = "15";
		let x = i32::from_str(s).unwrap();

		assert_eq!(15, x);
		println!("The converted number is :");
		println!("{}", x + 1);

}

Output

rustc -o main main.rs
./main
The converted number is :
16