Rust Lang

How to Convert String to Int Using Rust

Conversions are a popular task for most developers. They allow us to parse data from one format to another and perform the operations.

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:

let my_int: int_type = string.parse()

An example code is as shown below:

fn main() {

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:

let num = string.parse::<i32>().unwrap();

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:

fn main() {

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 string =3.14159;

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 ch = '5';

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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list