OneBite.Dev - Coding blog in a bite size

Convert Variable From Int To String In Rust

Code snippet for how to Convert Variable From Int To String In Rust with sample and detail explanation

In Rust, there are instances where you must convert an integer to a string. This article introduces two simple methods for achieving this.

Code Snippet: Convert Variable from Int to String in Rust

// Method 1: Using .to_string() method
let int_var = 10;
let str_var = int_var.to_string();
println!("{}", str_var);

// Method 2: Using format! macro
let int_var = 20;
let str_var = format!("{}", int_var);
println!("{}", str_var);

Code Explanation: Convert Variable from Int to String in Rust

This tutorial guides you through the two methods demonstrated in the code snippet, providing a step-by-step explanation.

Using .to_string() Method

The first method utilizes the .to_string() method. Here, we define a variable int_var and assign an integer value of 10 to it. Next, the to_string() method is called on int_var, converting the integer into a string. This string is then stored in the str_var variable. Finally, we print str_var.

Using format! Macro

The second method employs the format! macro, a more flexible alternative as it can handle more data types and formats.

Just like in the first method, we start by defining an integer int_var and assigning the number 20 to it. We then use the format! macro to convert the integer into a string. The syntax "{}" is a placeholder that will be replaced by int_var. The resulting string is stored in str_var and finally printed.

Both methods will correctly convert the integer into a string. The Rust language ensures the safe conversion of variables, thereby preventing unexpected errors that may arise from incorrect data types conversions. So, you can confidently choose the method that serves your requirements best.

rust