home ~ projects ~ socials

Convert A String Into An Integer In Rust

Using turbofish

value.parse::<i32>()
fn main() {
  let value = "1";
  match value.parse::<i32>() {
    Ok(num) => { dbg!(num); () },
    Err(e) => { dbg!(e); () }
  }
}
Output:
[_active_nvim_run:4:18] num = 1

Using Explicit Type Annotation

NOTE: .parse() returns a Result which is just pulled with .unwrap() without any error handing in this example

fn main() {
  let value = "2";
  let num: i32 = value.parse().unwrap();
  dbg!(num);
}
Output:
[_active_nvim_run:4:3] num = 2
-- end of line --