Programming-Idioms

History of Idiom 22 > diff from v24 to v25

Edit summary for version 25 :
[Rust] Severed 2 syntaxes -> 2 impls

Version 24

2015-12-30, 21:19:20

Version 25

2015-12-30, 21:19:56

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
  }
};
  
Code
let i = s.parse::<i32>().unwrap();
Comments bubble
String is parsed to 32-bits signed integer here, but you can change number type to whatever you want.
Comments bubble
This panics if s is not a valid number.
s is parsed to 32-bits signed integer here, but you can change number type to whatever you want.