Programming-Idioms

History of Idiom 22 > diff from v6 to v7

Edit summary for version 7 :

Version 6

2015-08-03, 22:57:56

Version 7

2015-08-18, 14:57:04

Idiom #22 Convert string to integer

Extract integer value i from its string representation s (in radix 10)

Idiom #22 Convert string to integer

Extract integer value i from its string representation s (in radix 10)

Code
// Terminate (panic) program if string is invalid number
let i = s.parse::<i32>().unwrap();

// Analyze parsing error
let i = match s.parse::<i32>() {
  Ok(i) => i,
  Err(e) => {
    // parse error handling code here,
    // usually break out of function
    // or provide a sensable default, e.g.:
    0
  }
};
  
Comments bubble
String is parsed to 32-bits signed integer here, but you can change number type to whatever you want.