w3resource

Rust Program: Integer-String conversion

Rust Basic: Exercise-4 with Solution

Write a Rust program that converts an integer to a string and vice versa and prints the result.

Sample Solution:

Rust Code:

fn main() {
    // Convert integer to string
    let integer_value = 42;
    let string_value = integer_value.to_string();
    println!("Integer to string: {}", string_value);

    // Convert string to integer
    let string_value = "123";
    let parsed_integer: Result = string_value.parse();
    match parsed_integer {
        Ok(int_value) => println!("String to integer: {}", int_value),
        Err(_) => println!("Failed to parse string to integer"),
    }
}

Output:

Integer to string: 42
String to integer: 123

Explanation:

Here's a brief explanation of the above Rust code:

  • Convert integer to string:
  • We declare an integer variable 'integer_value' and initialize it with the value 42.
  • We use the "to_string()" method to convert 'integer_value' to a "String" and store the result in the variable 'string_value'.
  • We print the converted string value using "println!()".
  • Convert string to integer:
  • We declare a string variable 'string_value' and initialize it with the string "123".
  • We use the parse() method to parse 'string_value' into an integer. Since parse() returns a 'Result', we use pattern matching (match) to handle both success and error cases.
  • In the success case (Ok(int_value)), we print the parsed integer value.
  • In the error case (Err(_)), we print a message indicating parsing failure.

Rust Code Editor:

Previous: Rust Program: Variable counter operations.
Next: Rust Math Operations: Addition, Subtraction, Multiplication, Division.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/rust/basic/rust-basic-exercise-4.php