Câu hỏi phỏng vấn Rust
Câu hỏi

Is there a way to directly convert a String to an int ?

Câu trả lời

Yes, there is a way to directly convert a String to an int in Rust. The most common method to achieve this is by using the parse method provided by Rust's standard library. Here is a detailed explanation of how to do it:

Using the parse Method

The parse method is a generic function that can convert a string slice (&str) or a String into a specified type, such as an integer. The method returns a Result type, which can be either Ok(T) if the conversion is successful or Err(E) if it fails. Here is how you can use it:

Example Code

rust Copy
fn main() {
    let my_string = "42".to_string();
    let my_int: i32 = my_string.parse().unwrap();
    println!("{}", my_int); // Outputs: 42
}

In this example:

  • my_string is a String containing the value "42".
  • The parse::<i32>() method attempts to convert the string to a 32-bit signed integer.
  • The unwrap() method is used to handle the Result, panicking if the conversion fails.

Handling Errors

Instead of using unwrap(), which will panic on error, you can handle errors more gracefully using a match statement:

rust Copy
fn main() {
    let my_string = "42a".to_string();
    match my_string.parse::<i32>() {
        Ok(n) => println!("Number: {}", n),
        Err(e) => println!("Error: {}", e),
    }
}

In this example, if the string cannot be parsed into an integer, the error is caught and printed instead of causing a panic.

Trimming Input

When reading input from a user or another source, it is often useful to trim whitespace before parsing:

rust Copy
use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Failed to read line");
    let trimmed = input.trim();
   ...
junior

junior

Gợi ý câu hỏi phỏng vấn

junior

What happens when you pass a String to a function in Rust?

expert

What are the specific conditions for a closure to implement the Fn , FnMut and FnOnce traits?

middle

Explain what is Trait in Rust? What are some use cases when you need to implement one?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào